function jiahao(){
var a = document.getelementbyid("shuzi").value; // ❌ 大小寫錯誤
if (a <= 8) { a += 1; } else { a = a; }
document.getelementbyid("shuzi").value = a; // ❌ 字符串拼接而非數值相加
}
三大錯誤: 1. `getElementById` 大小寫 2. 未轉數字導致字符串拼接 `"8" + 1 = "81"` 3. 邏輯冗餘。
<input type="text" id="shuzi" value="0" readonly>
<button onclick="jiahao()">+1</button>
<script>
function jiahao() {
const input = document.getElementById("shuzi"); // ✅ 正確大小寫
let val = parseInt(input.value, 10) || 0; // ✅ 轉數字,防非數字報錯
if (val < 8) { // ✅ 邏輯簡化:小於8才加,等於8不加
val += 1;
}
// val = Math.min(val + 1, 8); // 更簡潔寫法
input.value = val; // ✅ 賦值數字,自動 toString()
}
</script>
<div class="counter">
<button id="btn-dec" aria-label="減少">−</button>
<input type="text" id="counter-val" value="0" readonly aria-label="計數值">
<button id="btn-inc" aria-label="增加">+</button>
</div>
<script>
const input = document.getElementById('counter-val');
const MIN = 0, MAX = 8;
function setValue(v) {
input.value = Math.max(MIN, Math.min(MAX, parseInt(v) || 0));
}
document.getElementById('btn-inc').addEventListener('click', () => setValue(input.value + 1));
document.getElementById('btn-dec').addEventListener('click', () => setValue(input.value - 1));
// 鍵盤支持
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp') setValue(input.value + 1);
if (e.key === 'ArrowDown') setValue(input.value - 1);
});
// 長按加速 (可選)
let timer, speed = 200;
['btn-inc', 'btn-dec'].forEach(id => {
const btn = document.getElementById(id);
const delta = id === 'btn-inc' ? 1 : -1;
btn.addEventListener('mousedown', () => {
timer = setInterval(() => setValue(input.value + delta), speed);
});
['mouseup', 'mouseleave'].forEach(evt =>
btn.addEventListener(evt, () => clearInterval(timer))
);
});
</script>
| 要點 | 錯誤寫法 | 正確寫法 |
|---|---|---|
| 獲取元素 | `getelementbyid` | `getElementById` (駝峰) |
| 值轉數字 | 直接用 `.value` | `parseInt(val, 10) \| \| 0` |
| 邊界控制 | if-else 硬編碼 | `Math.min/max` 或 `clamp` 函數 |
| 事件綁定 | 內聯 `onclick=""` | `addEventListener` 解耦 |
JS 基礎交互三板斧:**正確 API 大小寫**、**強制類型轉換**、**邊界條件防禦**。養成 `addEventListener` 解耦、語義化 HTML、無障礙屬性(`aria-label`)的習慣,代碼才專業、可維護。