开发者

How does the click() function in jquery work when working with multiple stacked divs?

How does the click() 开发者_如何学运维function in jquery work when working with multiple stacked divs?

I have one main div and another div inside of the main div, when i click on the div inside, its also considered a click on the main div, but i dont want that, i want it to only consider a click on the inside div.

<div id="main"><div id="inner"></div></div>

Lets say the main div is a lot larger and the innner div is just a small square, when i click on the inner div(small square) I dont want it to trigger anyting as if i were to click on the main div. How do I maneuver this? Thanks again!


Events bubble up from the one that was clicked, through all its ancestors. Any ancestor that handles that event will have its handler fired.

What you need to do is to call event.stopPropagation() in order to prevent the event from bubbling up to its ancestor elements.

$('#inner').click(function(evt) {
    evt.stopPropagation();
    // your code
});
  • http://api.jquery.com/event.stopPropagation/

Another alternative is to return false; at the end of your handler.

$('#inner').click(function(evt) {
    // your code
    return false;
});

You can test it out here: http://jsfiddle.net/ZpeYr/


$('#inner').click(function() {  
  alert('clicked inner div'); // do something
});

you can call your inner div using using the css id.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜