想練習 DOM 取值與型別轉換,加法計算器是最經典的入門題。它涵蓋了 getElementById 取值、parseInt 轉型與回寫結果三個基本動作。
從輸入框取到的 value 一律是字串,若直接寫 a + b,瀏覽器會進行字串串接,10 加 20 會得到「1020」。因此必須先用 parseInt(value, 10) 明確轉成十進位數字。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function sum() {
// parseInt(value, 10) 的意義是把 value 轉成十進位數值
var id1 = parseInt(document.getElementById("bnt1").value, 10);
var id2 = parseInt(document.getElementById("bnt2").value, 10);
var id3 = id1 + id2;
document.getElementById("bnt3").value = id3;
}
</script>
</head>
<body>
<input type="text" id="bnt1" />+
<input type="text" id="bnt2" />
<input type="button" value="=" onclick="sum()" />
<input type="text" readonly="readonly" id="bnt3" />
</body>
</html>
isNaN() 檢查轉型是否失敗,避免出現 NaN。parseInt 換成 parseFloat。readonly,避免使用者誤改運算結果。onkeydown 攔截 Enter 鍵,操作會更順。這個小範例把型別轉換與 DOM 讀寫串在一起,是理解前端資料流很好的起點。