使用 document.getElementsByClassName('zuo2') 獲取元素集合後,直接綁定事件無效,因為返回的是 HTMLCollection,不具備事件綁定方法。
var oZuolist = document.getElementsByClassName('zuo2');
for (var i = 0; i < oZuolist.length; i++) {
oZuolist[i].onmouseover = function() {
// 此處使用 this 指向當前觸發事件的元素
this.style.backgroundColor = 'yellow';
};
}
getElementsByClassName 返回即時集合,需循環為每個元素單獨綁定事件。i,改用 this 獲取當前元素。addEventListener 替代 onmouseover,支持多事件監聽。若元素數量大或動態增減,可在父容器綁定單一事件,利用事件冒泡判斷目標:
document.getElementById('parent').addEventListener('mouseover', function(e) {
if (e.target.classList.contains('zuo2')) {
e.target.style.backgroundColor = 'yellow';
}
});
掌握集合遍歷與事件委託,靈活應對批量元素交互需求。