document.getElementById("t3").value = document.getElementById("t1").value +
document.getElementById("t2");
通過上面的代碼我無法獲得兩個數字相加的結果。在Javascript中使用文本框的「.value」屬性
document.getElementById("t3").value = document.getElementById("t1").value +
document.getElementById("t2");
通過上面的代碼我無法獲得兩個數字相加的結果。在Javascript中使用文本框的「.value」屬性
如果您想將這些添加到值,您必須首先將它們轉換爲整數。 .value
始終保存一個字符串。
parseInt(document.getElementById("t1").value, 10) + parseInt(document.getElementById("t2").value, 10);
如果您必須使用'parseInt',則還需要使用radix參數。 – lonesomeday
@lonesomeday好點,雖然我相信它默認以10爲基礎ECMAScript 5 – Moob
@Moob而當字符串是'012'?符合ECMAScript 5的瀏覽器將使用base 10,但其他人可能不會。那麼'0x12'呢?您希望瀏覽器如何對待它? (所有這些問題都可以通過使用一元加運算符來解決......) – lonesomeday
你實際上並沒有把兩個數字加在一起。您正在嘗試將document.getElementById("t1").value
(這是一個包含數字的字符串)添加到document.getElementById("t2")
,這是一個DOM元素。
你可能得到的結果是這樣的:
43[object HTMLInputElement]
你需要(一)獲得的第二個元素的value
財產和(b)一起添加這些數字,而不是字符串。
document.getElementById("t3").value = (+document.getElementById("t1").value) +
(+document.getElementById("t2").value);
(+document.getElementById("t1").value)
將該值轉換爲數字。這是unary plus +
operator。
這是厚臉皮的,但在關機會t3
元素的OP試圖更新是div
或span
而非input
:)
var t1, t2, t3;
t1 = document.getElementById("t1");
t2 = document.getElementById("t2");
t3 = document.getElementById("t3");
t3.innerHTML = parseInt(t1.value, 10) + parseInt(t2.value, 10);
或者
t3.innerHTML = +t1.value + +t2.value;
極品更多信息;什麼樣的元素是#t3? – Paul
表單控制值是字符串,因此'+'將字符串連接起來,而不是執行數字的添加。 – RobG
你可以給我們整個HTML和JavaScript片段?你爲什麼要綁定什麼事件? – chaseadamsio