How do I attach event handlers using jQuery only to newly added elements?
There are objects where I have attached some events to. After some point, I create some more of those items and I want them also to be attached to the same events.
If select elements using a jQuery selector and att开发者_运维知识库ach the handler to the event, the older object will have the same handler attached multiple times to their event.
What's the proper way of doing this?
Perhaps you should consider adding the handlers with live
instead. This way, you declare the handler once and it remains in effect for all matching elements, now and in the future.
If for some reason this is not acceptable, a quick and dirty solution would be (example for the click
handler):
$(".elements").unbind("click").bind("click", function () {
// ...
});
A much better solution (again, without live
) would be the hasEventListener
plugin. Read the documentation, or play with its sandbox on JSFiddle.
I would go like this about it:
$(".element").unbind("click").live("click", function () {
// ...
});
and by that you unbind older 'click' event handlers and bind old and new ones only once with live
.
The easiest way would be to use .live()
to keep your handlers binded for existing and any possible future elements that match given selector.
Use a namespace for your events, like so:
$('a').bind('click.customNS', function(){...})
and then, whenever you create a new element, unbind all of your namespaces events, and rebind, like so:
$('a').unbind('click.customNS');
$('a').bind('click.customNS', function(){...});
alternatively, use .live('click', function(){..});
, which will automatically "bind" events to any newly created element, matchin your jQuery selector. This does not work on non-CSS compliant selectors, though. (jQuery special parent-selectors, for instance)
精彩评论