假设我有以下代码:
<div class="body">
Click me and it will work.
<div class="head">Click me and nothing will happen.</div>
</div>当你在.body目录中点击而不是在.head目录中点击时,我想显示"it works“。我该怎么做呢?
使用此代码时,即使您单击head,日志也会显示
<script>
$('.body').click(function(){console.log('it works !');});
</script>发布于 2012-01-29 22:26:01
事件冒泡正在给您带来麻烦。本质上,您的'head‘类的事件处理程序将捕获单击,然后将该事件冒泡到您的'body’处理程序中,因为存在嵌套。
Here is an excellent primer on event bubbling, how it works, and how to control event bubbling.
下面是供您测试的工作jsFiddle example。
发布于 2012-01-29 22:14:09
$('.body').click(function(e){
if($(e.target).hasClass('body'))
console.log('it works !');
});发布于 2012-01-29 22:18:24
这叫做事件冒泡。当你点击"head“div时,你同时也点击了"body”div。
您需要添加:
$('.head').click(function(event){event.stopPropagation()});以防止事件冒泡。
https://stackoverflow.com/questions/9053806
复制相似问题