Reputation: 22568
Is the following delegated across both <div>
tags? ie: one or two event handlers? I need to capture the data-id
on the event.delegateTarget. This is simple when attaching to each of the <div>
tags but I may have 20 or so of these. Guessing not a big deal either way, but I would like a better understanding.
The jQuery Docs state that if I provide the selector
for the on
method, it is delegated but my scenario seems to be a slightly different case where I am attaching to multiple elements. Is there a way I can see the resulting event handlers using my browsers debugger tools?
If I attach my handler to the document
, is there any easy way I can capture the containing div
? My document is quite a bit more complicated than the example and I can't simply rely on the fact that the div
and associated data-id
is a direct parent of the input
elements.
$(".target").on("change", "input", function (event) {
...
});
<div class="target" data-id="123">
<input type="checkbox" name="alpha" value="1" />
<input type="checkbox" name="alpha" value="2" />
</div>
<div class="target" data-id="789">
<input type="checkbox" name="beta" value="3" />
<input type="checkbox" name="beta" value="4" />
</div>
Upvotes: 1
Views: 120
Reputation: 71918
I believe that's two separate delegations, if that's what you're asking. A separate reference to the handler function is attached to each of the two .target
divs, and each one handles the events triggered by their own pair of checkboxes.
If you bind to a common ancestor of both divs, you can always find the containing div by using $(this).closest('.target')
, as Pointy suggested.
Upvotes: 1
Reputation: 413717
It's one handler function that'll be called for "change" events on <input>
elements in either of the two <div>
elements.
The real event handler is a jQuery internal thing, that examines the event target and dispatches appropriately.
If you attach to the <body>
, you'd do this:
$('body').on('change', '.target input', function() { ... });
From the handler, this
will be the <input>
and you can use .closest('.target')
to find the container.
Upvotes: 3