我建议(除非您明确需要反向迭代):
var els = document.getElementsByClassName('item'),
l = els.length,
foo = function () { alert("foo"); };
for (var i = 0; i< l; i++) {
els[i].onclick = foo;
}
JS 小提琴演示。
您的代码存在问题:
// 'Length' should be 'length':
var l = document.getElementsByClassName("item").Length;
var foo = function () { alert("foo"); };
// since you're not changing the class-name there's no need to
// go in reverse (it's just confusing to read):
for (var i = l - 1; i >= 0; i--) {
// you're re-querying every iteration (plus when you're getting the length), why?
// keeping the parentheses assigns the (non-existent) return value of the function,
// instead of binding the function to the 'click' event:
document.getElementsByClassName("item")[i].onclick = foo();
}
顺便说一句,您可以将事件处理程序绑定到最近的祖先元素,该元素包含您希望在单击它们时产生效果的所有元素(注意:使用事件绑定时 DOM 中存在的最近的祖先元素,在这种情况下是body
,因为没有其他包装元素,在大多数情况下会有,并且应该使用最接近的元素以避免事件必须一直冒泡到“顶部”):
var bindTarget = document.body, // use the closest wrapping element
foo = function (e) {
var e = e || window.event,
clicked = e.target || e.srcElement;
if (clicked.className.indexOf('item') > -1) {
alert("foo");
}
};
bindTarget.onclick = foo;
JS 小提琴演示。