jQuery, use the right selector
I have a div, inside which there is a some text and a number of words surrounded by certain span tags. I want to click on those "spanned" words and have the div slide down, showing an "underlying" div with a text related to that certain spanned word. When i click on the div and not on a spanned word, i want the div to slide back up. Thus i bound some actions to the div and to the class of those spans. however, when i click on a span, the 开发者_StackOverflowdiv also gets the click action. How should i change the selectors not to receive a clicking action on the div when i click on the span?
Here is the code:
<div class='mainpage'>
<p class='common'>bla-bla-bla <span class='footnoted' footnote='f1'>foo bar</span></p>
</div>
jQuery code:
$(document).ready(function(){
$(".mainpage>.common>.footnoted").click(function(){
alert('a');
});
$(".mainpage").not($(".mainpage>.common>.footnoted")).click(function(){
alert('b');
});
});
In other words, when i click on "foo bar", i get the "a" and "b" alerts, whereas i want to get only "a". How can i do that?
Thank you in advance. Timofey.
You need to use
event.stopPropagation();
in the span like so
$('div').click(function(){alert('div clicked');});
$('div span').click(function(event){
alert('span clicked')
event.stopPropagation();
});
Live Demo
Reference
Depending on which event is firing first, you could try adding return false;
to the end of your click event function. That should stop the second click event from firing and fix your problem.
精彩评论