在动态创建的元素上添加事件侦听器 [英] add event listener on elements created dynamically
问题描述
是否可以向所有动态生成的元素添加事件监听器(javascript)?
我不是页面的拥有者,所以我不能以静态的方式添加一个监听器。
Is possible to add event listener (javascript) to all dynamically generated elements? I'm not the owner of the page, so I cannot add a listener in a static way.
为页面加载时创建的所有元素使用:
for all the elements created when the page loaded I use:
doc.body.addEventListener('click', function(e){
//my code
},true);
我需要一个方法来在页面上出现新元素时调用此代码,但我不能使用jQuery (委托,等等,不能在我的项目中工作)。我怎么能这样做?
I need a method to call this code when new elements appear on the page, but I cannot use jQuery (delegate, on, etc cannot work in my project). How can i do this?
推荐答案
听起来你需要追求一个授权策略而不会回到图书馆。我在这里的小提琴中发布了一些示例代码: http://jsfiddle.net/founddrama/ggMUn/
It sounds like you need to pursue a delegation strategy without falling back to a library. I've posted some sample code in a Fiddle here: http://jsfiddle.net/founddrama/ggMUn/
它的要点是在事件上使用
反对寻找您感兴趣的元素,并做出相应的反应。类似于:目标
The gist of it is to use the target
on the event
object to look for the elements you're interested in, and respond accordingly. Something like:
document.querySelector('body').addEventListener('click', function(event) {
if (event.target.tagName.toLowerCase() === 'li') {
// do your action on your 'li' or whatever it is you're listening for
}
});
CAVEATS!示例小提琴仅包含符合标准的浏览器的代码(即IE9 +,几乎每个人的每个版本)如果你需要支持旧IE attachEvent
,那么你还需要提供自己的自定义包装器围绕适当的原生功能。 (关于这一点有很多很好的讨论;我喜欢Nicholas Zakas在他的书专业JavaScript for Web Developers 中提供的解决方案。)
CAVEATS! The example Fiddle only includes code for the standards-compliant browsers (i.e., IE9+, and pretty much every version of everyone else) If you need to support "old IE's" attachEvent
, then you'll want to also provide your own custom wrapper around the proper native functions. (There are lots of good discussions out there about this; I like the solution Nicholas Zakas provides in his book Professional JavaScript for Web Developers.)
这篇关于在动态创建的元素上添加事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!