Reputation: 92691
i am slightly confused about how jquery's Delegate Function works.
If I have a variable called picker which contains.
This variable contains a div, which in turn contains an unknown amount of spans.
I am looking to setup some click handlers on every single span inside the picker div.
Is delegate the best way to do this?
If so, How would I do this?
Upvotes: 0
Views: 1009
Reputation: 66042
So I'm assuming picker looks something like this:
var picker = $("div.someDiv");
And you want to attach click handlers to all span
elements that are child nodes of div.someDiv
using .delegate()
.
Here's how I'd go about it:
picker.delegate("span", "click", function(eventObj) {
// do what you want
});
.delegate()
works by taking advantage of the fact that most DOM events bubble, or propagate. .delegate()
is very similar to .live()
in this regard. Where .delegate()
differs is that instead of just attaching your handler at the document root, and firing your handler when your event bubbles all the way up, it attaches the event to the element that you pass to $()
, and then watches for events to bubble up from that element's children.
Upvotes: 3
Reputation: 120538
What's wrong with
$("#picker span").click(function(){
//I was clicked
});
?
Upvotes: 0
Reputation: 23354
Yep, you should be able to do it like:
picker.delegate("span", "click", function() {
// do something to $(this) here!
});
Upvotes: 2