Need ultimate parent of click target
Here's a question about binding click events with jQuery that I'm trying to make sense of.
Say I have a block element I bind a click to, with a paragraph tag inside of it:
<div id="testClick" style="width:200px; height:100px'>
<p>test click</p>
</div>
and I bind a click to the div:
$('#testClick').bind('click', function(e){
//with parent div (via e.target), do something
});
Now, if I click on the text inside the p tag, e.target
= the p element, and if I click on the div (around, not on the text) e.target = the div element. So e.target
= the object clicked on - i.e. the event is also bound to any children of the element specified.
This is to be expected, but I need operate on the parent div. and using e.target
is not a reliable way of getting a reference to the div, because depending where within the div the click occurs e.target returns a different element. If I use e.target.parent
to get a reference to the div, this fails when the click occurs in the div around the text.
Is there no simple way to get e.target
to always and only return the exact element to which the click was initia开发者_JAVA技巧lly bound?
(For example, in actionScript there is a property "mouseChildren" that prevents events from firing on children of bound elements)
(Consider all above pseudo code)
this
will reference the element to which the handler is bound.
$('#testClick').bind('click', function(e){
alert( this.id );
});
DEMO: http://jsfiddle.net/yX499/
What happens is that the event bubbles up from the most deeply element clicked all the way to the document root.
If it encounters an element along the way with a handler bound for the type of event that occurred, it invokes that handler.
e.target
will always reference that deeply nested element, but this
will reference the element to which the handler is bound, so if the event finds 2 elements with an appropriate handler bound on the way up to the root, e.target
will not change in the 2 handlers, but this
will be different based on the bound element.
Use this
. jQuery calls your callback with this
set for your convience:
$('#testClick').bind('click', function(e){
$(this).doStuff();
});
精彩评论