简体   繁体   English

排除Javascript / DOM中的元素

[英]Excluding Elements In Javascript / DOM

Given the html / css / javascript/jquery as follows, the event still fires when I click on '#bbb'. 给定html / css / javascript / jquery如下,当我单击“ #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. e.target指向触发click事件的DOM元素。 this points to the #aaa element (because it's his click handler). this指向#aaa元素(因为这是他的点击处理程序)。 Therefore, this line 因此,这条线

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

will terminate the click handler early if the #aaa element wasn't clicked directly. 如果未直接点击#aaa元素, #aaa提早终止点击处理程序。

Live demo: http://jsfiddle.net/qbDZy/ 现场演示: http //jsfiddle.net/qbDZy/

You want to cancel the event bubbling (event propagation) 您想取消事件冒泡(事件传播)
http://www.quirksmode.org/js/events_order.html 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. 根据我对bbb元素嵌套在aaa元素内的理解,您可能还必须处理bbb元素中的click事件。

$('#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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM