jQuery : give preference to inner click
I have a big div with some links inside, I'd like to have the big div clickable AND links inside too, I did this :开发者_开发百科
html :
<div class="clickable">
some text...
<a href="myurl1">Link 1</a>
<a href="myurl2">Link 2</a>
some text...
</div>
jquery :
$('.clickable').click(function() {
alert('Hello');
});
If I click on a link inside the clickable div, I got the 'Hello' alert first and then the new page is loaded : is that possible to get the anchors working without triggering the outer div click handler ?
Add this code:
$('a').click(function(event) {
event.stopPropagation();
});
You can see it working here: http://jsfiddle.net/wPymp/
This code works in a simple way: .event.stopPropagation()
makes sure the event does not propagate upwards across the DOM and trigger handlers on ancestor elements.
精彩评论