我正在做一个简单的 JS DOM 练习。它应该乘以用户在输入框中输入的两个变量的面积。但是就在我以为我完成了它时,我的代码却不起作用。
var one = document.getElementById("one").value;
var two = document.getElementById("two").value;
var output = document.getElementById("output");
function calculate() {
output.innerHTML = one * two;
}
var button = document.getElementById("button");
button.onclick = calculate();
<h1>Area Calculator for Rectangles</h1>
<form>
Side Length One<br>
<input type="text" id="one"><br> Side Length Two<br>
<input type="text" id="two">
</form>
<button id="button">SUBMIT</button>
<p id="output"></p>
最佳答案
首先,您必须在单击按钮时获取值。因此,将它移到 calculate()
函数中。其次,您必须为 onClick
属性分配一个函数。所以,不要执行它,只是分配像prop=funName
这样的函数。
var one, two;
var output = document.getElementById("output");
function calculate() {
one = document.getElementById("one").value; //Change1
two = document.getElementById("two").value; //Change1
output.innerHTML = one * two;
}
var button = document.getElementById("button");
button.onclick = calculate; //Change2
<h1>Area Calculator for Rectangles</h1>
<form>
Side Length One<br>
<input type="text" id="one"><br> Side Length Two<br>
<input type="text" id="two">
</form>
<button id="button">SUBMIT</button>
<p id="output"></p>
正如评论中提到的@mplungjan
,最好使用window.onload
监听器来确保所有的dom元素都完成加载(在尝试访问它们之前) .
关于JavaScript 面积计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43315457/