开发者

Excluding Elements In Javascript / DOM

Given the html / css / javascript/jquery as follows, the event still fires when I click on '#bbb'.

Is there anyway to avoid this from happening?

<div id="aaa" style="position:absolute; width:100%; height:100%; background-color:#f00;">
   <div id="bbb" style="height:25%; width:25%; background-color:#0f0; margin:0 auto;">
   </div>
</div>

<script type="text/javascript">
   $('#aaa').click(function(){alert('aaa clicked');})开发者_运维百科;
</script>


Here you go:

$( '#aaa' ).click(function (e) { 
    if ( e.target !== this ) { return; }
    alert( 'aaa clicked' );
});

e.target points to the DOM element at which the click event was fired. this points to the #aaa element (because it's his click handler). Therefore, this line

if ( e.target !== this ) { return; }

will terminate the click handler early if the #aaa element wasn't clicked directly.

Live demo: http://jsfiddle.net/qbDZy/


You want to cancel the event bubbling (event propagation)
http://www.quirksmode.org/js/events_order.html

DEMO HERE

$('#aaa').click(function(){alert('aaa clicked');});
$('#bbb').click(function(event){alert('bbb clicked');  event.stopPropagation();});   


From my understanding as bbb element is nested within aaa element, you will probably have to handle click event in bbb element as well.

$('#aaa').click(function(event){event.stopPropagation(); alert('aaa clicked');});
$('#bbb').click(function(event){event.stopPropagation(); alert('bbb clicked');});

But do not forget to consider stoping event propagation or both event listener will get notified.

You can see source code in action here

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜