Is it possible to get开发者_JAVA技巧 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:
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);
};
Since the event handler is attached to the parent, it will work for any future elements inserted.
You can try it here.
Useful reference:
- http://www.quirksmode.org/js/events_properties.html#target
- http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
Yes, it's called event delegation and has been around longer than jQuery and "live".
"live" works by listening for events on the body or document, then when when an event occurs looks at the event.target to see if it's selector matches one of those stored in a cache. It is quite inefficient, but works OK for some.
A more efficient approach is to add elements you want listeners on to an array, then listen for bubbling events on the lowest common ancestor of the elements you want to delegate events for. The body element is the fallback, but it's the least efficient. When the listener gets an event it's waiting for, check if the event.target is one of the elements in the array and if so, call the related function with the element as this.
You can also just store the element id as a property of an object so looking it up is faster if you have lots of elements, or you can register events based on class.
There are a few limitations and foibles (some events bubble in some browsers but not others, and some don't bubble at all), and it can be very inefficient, so use with care.
I know little of Jquery and your functions. You are looking how works with events in javascript? You can make this:
element.addEventListener('onclick',
function() {
//do something
});
or
element.onclick =
function() {
//do something
});
the element
var is an reference of dom document.
check https://developer.mozilla.org/en/DOM for more details.
JQuery is pure JavaScript and OpenSource, so just have a look into the sources, then copy what you need and adapt it.
精彩评论