Get the selector of a .delegate
In this code I need to get the DOM object that is .tabs
the original selector that the delegate is wired up against.
$(".tabs").delegate("li:not(.selected) a", "click", function () {
// ^
// |
// +-----------i need to get this dom object
var selector = $(this).selector; // <---- returns an empty string ?
return false;
});
How to determine what .tabs
is and access the object?
Until someone finds a smarter way, a workaround could be to attach an event handler to the selected elements themselves:
$('.tabs').click(function(event) {
event.root = this; // or whatever name suits you best
});
$(".tabs").delegate("li:not(.selected) a", "click", function (event) {
// event.root contains the DOM element
});
jQuery guarantees that event handlers are executed in the order they are attached.
Or you don't use delegate
at all and make the selector test yourself (this is probably the best solution):
$('.tabs').click(function(event) {
if($(event.target).is("li:not(.selected) a")) {
// this refers to the .tab DOM element
// event.target refers to the originally clicked element
}
});
Update:
The original Event
object is available via event.originalEvent
. So you could do:
$(".tabs").delegate("li:not(.selected) a", "click", function (event) {
var dom = event.originalEvent.currentTarget;
});
But it seems currentTarget
is only supported in IE9 and there is no alternative in lower IE versions.
So the most cross-browser compatible solutions are still the ones above.
With the .on()
method, you can access the delegated target by passing the event object to your function and accessing its delegateTarget
property.
Example:
$('.foo').on('click', 'a', function(ev) {
// this is the .foo element for this anchor
console.log(ev.delegateTarget);
});
Working Example: http://jsfiddle.net/corydorning/ZzADh/
精彩评论