简体   繁体   English

将onclick分配给整个班级

[英]Assign onclick to entire class

I'm trying to attach an event handler on all elements with a specific div. 我正在尝试将事件处理程序附加到具有特定div的所有元素上。 I have created a jsfiddle showing an example of my code. 我创建了一个显示我的代码示例的jsfiddle。 Could someone please point me in the right direction? 有人能指出我正确的方向吗?

http://jsfiddle.net/nw4Xs/ http://jsfiddle.net/nw4Xs/

var l = document.getElementsByClassName("item").Length;
var foo = function () { alert("foo"); };
for (var i = l - 1; i >= 0; i--) {
    document.getElementsByClassName("item")[i].onclick = foo();
}

please no jquery answers 请没有jQuery的答案

Thanks 谢谢

I'd suggest (unless you explicitly need to iterate in reverse): 我建议(除非您明确需要反向迭代):

var els = document.getElementsByClassName('item'),
    l = els.length,
    foo = function () { alert("foo"); };

for (var i = 0; i< l; i++) {
    els[i].onclick = foo;
}

JS Fiddle demo . JS小提琴演示

Problems with your code: 您的代码有问题:

// '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();
}

Incidentally, you could instead bind the event-handler to the closest ancestor element that wraps all the elements you want to have an effect when they're clicked (note: use the closest ancestor that exists in the DOM at the time of event-binding, in this case it's the body , because there's no other wrapping elements, in most cases there will be, and the closest should be used to avoid events having to bubble all the way to the 'top'): 顺便说一句,您可以将事件处理程序绑定到最接近的祖先元素,该元素包装您希望在单击时起作用的所有元素(请注意:使用事件绑定时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 Fiddle demo . JS小提琴演示

The property of a NodeList (what getElementByClassName() returns) that you want is length (lowercase). 所需的NodeList属性( getElementByClassName()返回的属性)是length (小写)。

To pass a reference to a function, just use its name; 要传递对函数的引用,只需使用其名称即可; don't put parentheses after it. 不要在其后加上括号。 Otherwise you're calling the function and assigning or passing its return value. 否则,您将调用该函数并分配或传递其返回值。

var items = document.getElementsByClassName("item");
var l = items.length;
var foo = function () { alert("foo"); };
for (var i = l - 1; i >= 0; i--) {
    items[i].onclick = foo;
}

You can call Array.prototype.forEach over the result of document.getElementsByClassName("item") 您可以在document.getElementsByClassName("item")的结果上调用Array.prototype.forEach

var foo = function () { alert('foo'); };

Array.prototype.forEach.call(document.getElementsByClassName('item'), function ( item ) {
    item.addEventListener('click', foo);
});

Fiddle: http://jsfiddle.net/nw4Xs/7/ 小提琴: http : //jsfiddle.net/nw4Xs/7/

If you are interested in using jQuery, you can write this out a lot simpler. 如果您对使用jQuery感兴趣,则可以将其编写得更加简单。 Whilst it's not necessary it may save you a lot of time in the future when you are trying to do harder stuff. 尽管没有必要,但是当您尝试做更艰苦的工作时,可能会在将来节省很多时间。 At a basic level: 在基本层面上:

function foo...

$(".item").click(foo);

This will get all DOM elements with a class of "item" and attach foo to the click event. 这将获得所有带有“ item”类的DOM元素,并将foo附加到click事件。 If you're interested, there is lots of documentation and help with using jQuery. 如果您有兴趣,可以找到许多有关使用jQuery的文档和帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM