click events on nested list items each with their own click handler
I have nested unordered lists and click handlers on each li element. When clicking on a nested li, it's firing both events. Is there anyway to prevent this behavior?
<ul>
<li>thundercats
<ul>
<li>panthero</li>
<li>cheetarah</li>
</ul>
</li>
</ul>
So in the above list clicking "thundercats" would fire one event setting a value to "thundercats", clicking on panthero would fire another event setting a value to panthero.
Unfortunately clicking panthero causes the value to be set properly for an instant an开发者_Go百科d then the click handler on thundercats fires and overwrites the value. Is there a way to prevent that?
One option is to prevent the event bubbling up the DOM tree. This will work, but it's not optimal because sometimes event bubbling is very useful. It's nicer to check to see if the event originated on the correct element:
$('li').click(function(event) {
if (this === event.target) {
// do your code
}
});
This code works because this
and event.target
both point to DOM elements. this
is the element where the event handler is handled (where the code is run) while event.target
is the element where the event originated, i.e. the element that was clicked. If they are the same element, the event was triggered on the same element as where it is being handled; this is where you want the code to be run, and nowhere else. Comparing the elements with ===
accomplishes this.
You need to use event.stopPropagation
. This will keep the click event from bubbling up the DOM tree.
$(document).ready( function () {
$('li').click(function (evt) {
// Your code here
// Stop the event propagation
evt.stopPropagation();
})
});
It should be as simple as adding:
return false;
...to your event handler function.
When an event handler returns false, it stops event propagation (it's effectively the same as calling .preventDefault() and .stopPropagation() on the event object). It'd definitely be helpful to see your code, but it sounds like this will do it.
精彩评论