Suppose I have the following HTML:
<div class="container">
<span class="remove">remove</span>
</div>
and jquery:
$(".container").delegate(".remove", "click", function() {
alert('yes');
});
This works, but now I have HTML like:
<div class"container">
<div>
<span class="remove">remove</span>
</div>
</div>
or even
<div class"container">
<div>
<div>
<span class="remove">remove</span>
</div>
</div>
</div>
So how can I make the jquery work in this case, so that if finds the .remove element in a hierarchy of elements and make the click event work?
NOTE: I’m adding the elements dynamically (using clone function)!
This will still work. As long as the element you’re delegating the event to is an ancestor of the element, the element will receive the event.
An exception to this is where an element which is a more direct ancestor stops the propagation of the event using
event.stopPropagation(),event.stopImmediatePropagation(), or by returningfalsein it’s handler;FYI, if you’re using jQuery > 1.7, you should consider using the new
on()method ason()was implemented to disperse the confusion overlive(),delegate()andbind(). It is expected that these older methods will be depreciated in 1.8. The following is equivilent for what you’re currently using;