例如
<div class="container">
<div class="inside">I am not fire when click me</div>
</div>
$('.container').click(function(){
// container do something here
});
Run Code Online (Sandbox Code Playgroud)
但是,当我单击其中的div时,它也会触发容器的click事件,因为div位于容器内部,因此,当我点击内部div时,我需要一种方法来阻止容器事件触发!
非常感谢你!!
jos*_*736 13
作为一个更通用的解决方案,你应该检查e.target中container的click事件处理程序.
$('.container').click(function(e) {
// If you want to ignore clicks to anything inside the `.container` div:
if (!$(e.target).hasClass('container')) return;
// or, if you only want the `.inside` div to not fire the event,
if ($(e.target).hasClass('inside')) return;
// container do something here
});
Run Code Online (Sandbox Code Playgroud)
这样您就不会阻止事件的传播,这会破坏绑定的live处理程序.
$('.inside').click(function(e) {
e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)
这对你有用.它会阻止内部div中的任何点击冒泡到容器.
这是一个简单的例子 - http://jsfiddle.net/Yf8Ra/1/