简单版的jquery live函数 [英] simple version of jquery live function
本文介绍了简单版的jquery live函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以获得具有与jquery的 live()
类似功能的事件处理程序的纯javascript函数?我需要能够将事件附加到尚未创建的对象,但由于依赖于jquery核心,jquery-livequery和jquery-events源都没有用。
Is it possible to get anywhere a pure javascript function for event handler with similar functionality as jquery's live()
? I need to have the ability to attach events to objects not yet created but both jquery-livequery as well as jquery-events sources are not useful due to dependencies on jquery core.
推荐答案
事件委托非常简单。举个例子:
Event delegation is quite simple. Take this example:
加价:
<div id="container">
<p>Test</p>
<p>Test</p>
<p>Test</p>
</div>
<button id="add">Add new paragraph</button>
脚本:
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);
};
由于事件处理程序已附加到父项,因此它将适用于未来插入的所有元素。
Since the event handler is attached to the parent, it will work for any future elements inserted.
有用的参考:
- http://www.quirksmode.org/js/events_properties.html#target
- http://www.sitepoint.com/javascript-event-delegation-is-easier-than-你认为/
- http://www.quirksmode.org/js/events_properties.html#target
- http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
这篇关于简单版的jquery live函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文