Reputation: 74410
I would like to change 'on the fly' selector of a delegated event.
For example,
i use this HTML:
<div id="div1">DIV1</div>
<div id="div2">DIV2</div>
<textarea id="result"></textarea>
i delegate a click event for all DIVs:
$(document).on("click", "div", function () {
$("#result").append(this.id + ' DIV click\r\n');
});
Later, i need to unbound a particular DIV. I could bound a new delegated event excluding this particular DIV and unbinding previous delegated event. However, in my case, i would like to keep previous event as it and just change the selector of this event, meaning, change event.selector
of delegated event on the fly.
This is the event:
var delegatedEvent = $._data(document, "events").click;
So trying to exclude a DIV by targeting its ID attribute (class, etc...) works, i can use e.g to exclude #div2
:
delegatedEvent[0].selector += ":not(#div2)"; // => selector == 'div:not(#div2)'
For some reason, i cannot target element using specific attribute, i need to use index of element:
var indexDiv2 = $(delegatedEvent[0].selector).index($("#div2")); // => 1
Now trying to exclude #div2 using its index doesn't work:
delegatedEvent[0].selector += ":not(:eq("+indexDiv2 +"))"; // => selector == 'div:not(:eq(1))'
Looks like matched set is reevaluated (???), if i use #div1
index (0), this will exclude all DIVs.
I'm stuck here, needing to use index to target specific DIV but cannot use it to modify a delegated event selector.
Any idea how to fix it or any known reason for this unexpected behaviour?
PS: i could use custom data-*
attribute (data-index) but still wondering why using :eq()
doesn't work...
Upvotes: 0
Views: 131
Reputation: 196296
Why not handle it with a dynamic class ?
$(document).on("click", "div:not(.exclude)", function () {
$("#result").append(this.id + ' DIV click\r\n');
});
And just add the class exclude
to the elements you want ? When you want it.
Upvotes: 1