如果你想获得一个单一的元素,那么getElementsByClassName
不叫,因为它返回元素的“活”的节点列表中的正确方法,这是过度,即使在你确实需要一系列元素的情况下也是如此。
取而代之的是,由于您的input
元素可以通过它们各自使用的不同类别单独标识,因此querySelector()
是单独使用它们的正确方法。
此外,请勿使用内嵌HTML事件处理属性(onclick
等),here's why。
现在,即使您确实掌握了所讨论的各个元素,所有HTML元素都只包含一种数据类型的字符串。在对它们进行数学计算之前,您必须将这些字符串转换为数字。
// Get a reference to the button
var btn = document.getElementById("calc");
// Set up a click event handler for the button
btn.addEventListener("click", myFunction);
function myFunction() {
// Get just the single elements you need and then trim any leading
// or trailing spaces off of the user's input and then convert that
// input into a number:
var x = parseFloat(document.querySelector(".input1").value.trim());
var y = parseFloat(document.querySelector(".input2").value.trim());
var result = x * y;
// Don't use innerHTML when you are suppling HTML as the value
// use textContent instead. This will perform better.
document.getElementById("results").textContent = result;
}
<input type="text" class="input1">
<input type="text" class="input2">
<button id="calc">Calculate</button>
<br>
<p id="results">Results</p>
因为一个'input'的值是一个字符串,而不是数字(NaN)。而'getElementsByClassName()'得到一个元素列表,而不仅仅是一个,它首先没有值。您必须先将这些值转换为数字。 –
用调试器几秒钟就可以创造奇迹。在乘以之前检查'x'和'y'的值。 –
有几个答案,所以更多的故障排除提示:您是否尝试过任何'console.log'语句来调查? 'console.log(foo)'和'console.log(typeof foo)'可能是有用的起点。 – shabs