开发者

jQuery : give preference to inner click

开发者 https://www.devze.com 2023-01-04 12:18 出处:网络
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 :开发者_开发百科

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消