是否有可能在任何地方获得一个纯 Javascript 函数用于事件处理程序,其功能与 jQuery 类似live()
?我需要能够将事件附加到尚未创建的对象,但由于依赖于 jQuery 核心,jquery-livequery 和 jquery-events 源都没有用。
事件委托非常简单。举个例子:
Markup:
<div id="container">
<p>Test</p>
<p>Test</p>
<p>Test</p>
</div>
<button id="add">Add new paragraph</button>
Script:
document.getElementById("container").onclick = function(e) {
// e.target is the target of the event or "source element"
alert(e.target.innerHTML);
};
// dynamically adds new paragraph on button click
document.getElementById("add").onclick = function() {
var p = document.createElement("p");
p.innerHTML = "a new paragraph";
document.getElementById("container").appendChild(p);
};
由于事件处理程序附加到父级,因此它将适用于将来插入的任何元素。
你可以在这里尝试一下。 http://jsfiddle.net/RWqrD/1/
有用的参考:
- http://www.quirksmode.org/js/events_properties.html#target http://www.quirksmode.org/js/events_properties.html#target
- http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/ http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)