javascript Javascript将事件附加到类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11273760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript attach event to class name
提问by Novak
If I have 10 items, with the class name keyword
:
如果我有 10 个项目,类名keyword
:
<div class="keyword"></div>
How can I attach an event, for example click
, on this element.
例如click
,如何在此元素上附加事件。
I tried the following, but with no luck: (no alert comes up)
我尝试了以下操作,但没有运气:(没有警报出现)
document.getElementsByClassName('.keyword').onclick = function()
{
alert(true);
Search.addKey(this.getElementsByClassName('name')[0].innerHTML);
}
Requirements:
要求:
- Without the onclick attribute
- no jQuery or any other library
- 没有 onclick 属性
- 没有 jQuery 或任何其他库
Note: the elements are not generated on page load. Their number can be different, each times you click a button for eg.
注意:元素不会在页面加载时生成。它们的数量可以不同,每次您单击按钮时,例如。
I need a way to attach to all tags with the class 'keyword' in the 'future'.
我需要一种方法将“未来”中的“关键字”类附加到所有标签。
回答by Elias Van Ootegem
You should delegate the event. Try this:
您应该委托该事件。试试这个:
if (document.body.addEventListener)
{
document.body.addEventListener('click',yourHandler,false);
}
else
{
document.body.attachEvent('onclick',yourHandler);//for IE
}
function yourHandler(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (target.className.match(/keyword/))
{
//an element with the keyword Class was clicked
}
}
You can read more on event delegation on quirksmode.com. AFAIK, this is the best way of achieving what you're trying to achieve. This is how all the major libs (prototype, jQuery, ...) work behind the scenes
您可以在 quirksmode.com 上阅读有关事件委托的更多信息。AFAIK,这是实现您想要实现的目标的最佳方式。这是所有主要库(原型,jQuery,...)在幕后工作的方式
Update:
更新:
Here's the fiddle, it contains some more explanation. An interesting reference is thispage. It helped me understand the way IE and W3C events differ and, crucialy, it helped me understand the value, and countless benefits of Event Delegation
这是小提琴,它包含更多解释。一个有趣的参考是这个页面。它帮助我理解了 IE 和 W3C 事件的不同之处,而且至关重要的是,它帮助我理解了事件委托的价值和无数好处