2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
calculate是一個(gè)返回?cái)?shù)字的函數(shù)。數(shù)字沒有value屬性。你想要的只是函數(shù)內(nèi)部的返回值,所以:
改變:
result.innerHTML = calculate(input1, input2).value;
至:
result.innerHTML = calculate(input1, input2);
而且,正如其他人在評論中指出的那樣,您的if聲明試圖將頁面中的元素與true.
相反,您應(yīng)該檢查元素包含的內(nèi)容。如果是表單域(輸入、選擇、文本區(qū)域等),請檢查元素的.value屬性。如果沒有,請檢查其.textContent屬性。現(xiàn)在,根據(jù)您的用例,您需要知道單擊了哪個(gè)按鈕,以便您可以執(zhí)行正確的數(shù)學(xué)運(yùn)算。為此,您需要處理click事件并執(zhí)行正確的操作。請參閱以下內(nèi)容以及可能的解決方案的評論:
// Get references to the elements you'll work with
let input1 = document.getElementById("one");
let input2 = document.getElementById("two");
let result = document.getElementById("result");
// Set up a click event hanlder at the document level
document.addEventListener("click", calculate);
function calculate(event) {
// First, check to see if the event originated at one of the math buttons
if(event.target.classList.contains("operator")){
// One of the operator buttons was clicked.
// Get the textContent of that button and do the appropriate math
let operation = event.target.textContent;
if(operation === "+"){
// The prepended + sign converts the string value to a number
result.textContent = +input1.value + +input2.value;
} else if(operation === "-") {
result.textContent = +input1.value - +input2.value;
} else if(operation === "*") {
result.textContent = +input1.value * +input2.value;
} else {
result.textContent = +input1.value / +input2.value;
}
}
}
<input id="one"><br>
<input id="two">
<button type="button" class="operator">+</button>
<button type="button" class="operator">-</button>
<button type="button" class="operator">*</button>
<button type="button" class="operator">/</button>
<br>
<span id="result"></span>

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
你為什么在 calculate(input1, input2).value 中做 .value ?因?yàn)槟悴皇欠祷匾粋€(gè)對象,而是一個(gè)數(shù)值,所以你不需要做 .value
使用 onclick 功能添加點(diǎn)擊事件
添加回答
舉報(bào)