趁著專案結束的空檔,寫了一段小程式來判斷「點的是第幾個按鈕」,程式碼如下:
<html>
<head>
<meta charset='utf-8'>
</head>
<body>
<button>第一個</button>
<button>第二個</button>
<button>第三個</button>
<button>第四個</button>
<button>第五個</button>
<script>
var but = document.getElementsByTagName('button');
for (i = 0; i < but.length; i++) {
but[i].setAttribute('i', i + 1);
but[i].onclick = function () {
b = this.getAttribute('i');
alert('這是第' + b + '個按鈕');
};
}
</script>
</body>
</html>
做法是在迴圈中把序號寫進自訂屬性,點擊時再透過 this 讀回來——this 指向被點擊的那個元素,因此每個按鈕都能回報自己的編號。
延伸:點擊後 60 秒才能再按
註冊時需要發送啟用信,為了避免重複寄送,可以在按下發送後讓按鈕暫時失效,倒數結束再恢復。
<html>
<head>
<title>點擊獲取驗證碼後按鈕變灰,倒數結束後可重複點擊</title>
</head>
<body>
<input type="button" id="btn" value="免費獲取驗證碼" />
<script type="text/javascript">
var wait = 60;
function time(o) {
if (wait == 0) {
o.removeAttribute("disabled");
o.value = "免費獲取驗證碼";
wait = 60;
} else {
o.setAttribute("disabled", true);
o.value = wait + "秒後可以重新發送";
wait--;
setTimeout(function () { time(o); }, 1000);
}
}
document.getElementById("btn").onclick = function () { time(this); };
</script>
</body>
</html>
這裡有兩個細節值得注意:一是計時器要傳入按鈕物件 o,才能在每次更新文字;二是倒數歸零時記得把 wait 重設回 60,否則第二次點擊會直接跳過倒數。