我决定制作一个假设计算器作为编码练习。它运行良好,但我无法将我的 Javascript 代码实现到 HTML 中。这是我的代码:
<!DOCTYPE html>
<html>
<head>
<script>
function getValueA() {
var a = prompt("What is value a?");
}
function getValueB() {
var b = prompt("What is value b?");
}
function hypothenuse(a, b) {
var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
return c
document.getElementById("result").innerHTML = "Answer is:" + str(c);
}
</script>
</head>
<body>
<p id="result">Answer:</p>
<button type="button" onclick="getValueA()">Input Value a</button>
<button type="button" onclick="getValueB()">Input Value b</button>
<button type="submit" onclick="hypothenuse()">Calculate</button>
</body>
</html>
过去的问题是返回的字符串是未定义
。但我在网站上做了一些研究后做了一些调整。最初,变量 a
和 b
位于一个名为 getData
的函数中,变量 c
等于函数 假设
。我移动了变量 c
,因为它在按下 Calculate
按钮之前调用函数。
所以现在字符串根本没有变化。我希望我的问题足够具体。
最佳答案
var a,b;
function getValueA() {
a = prompt("What is value a?");
}
function getValueB() {
b = prompt("What is value b?");
}
function hypothenuse(a, b) {
var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
document.getElementById("result").innerHTML = "Answer is:" + (c);
}
<p id="result">Answer:</p>
<button type="button" onclick="getValueA()">Input Value a</button>
<button type="button" onclick="getValueB()">Input Value b</button>
<button type="submit" onclick="hypothenuse(a, b)">Calculate</button>
有几件事,我们需要专注, 和
document.getElementById("result").innerHTML = "Answer is:" + (c);
有一个返回c;声明所以答案不会更新。 str(c) 在您定义 str() 的位置。 这是适合您的工作代码。
而且我们可以对仅输入大于零的数字进行额外验证。编写这些以获得更好的性能。
关于javascript - HTML 输入和 Javascript 不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30073444/