Jquery: Binding A Single Event Listener That Can Handle Events Of Its Children
$('ul.mylist').delegate('a', 'click', function() {
// ... your code ...
});
You get all the benefits of a jQuery handler, without having to do the binding to all those elements.
Solution 2:
You can access event.target
, which will be the element that started the event.
$('.myList').click(function(event) {
var target = $(event.target);
});
However, Pointy's answer seems to be easier to use.
Solution 3:
If you are using a version of jQuery >= 1.7 the .on()
method supplants .delegate()
. In both jQuery 2.x and 1.11.delegate()
simply calls .on()
:
delegate: function( selector, types, data, fn ) {
returnthis.on( types, selector, data, fn );
}
To use it in this case:
$(".myList li a").on("click", function(e) {
//Code here, and you can use e.preventDefault(); to avoid the default event.
});
Solution 4:
The function you attach will have an event parameter that contains the object which is clicked in event.target
.
$(.....).click(function(event){ .... });
Another solution, more complex, but more flexible too, although you won't need it in this situation, is to use the .bind
method and specify a data object
$(.....).bind('click', {whateverproperty: whatevervalue}, function(event){ ... });
In that case, you can reach event.data.whateverproperty
, thus retrieving the value whatevervalue
, allowing you to make more complex decisions.
Post a Comment for "Jquery: Binding A Single Event Listener That Can Handle Events Of Its Children"