如果你想獲得一個單一的元素,那麼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