在JQuery中单击容器内的元素时,如何取消容器div触发器的单击事件?

在JQuery中单击容器内的元素时,如何取消容器div触发器的单击事件?,jquery,events,Jquery,Events,例如 单击我时,我不是火 $('.container')。单击(函数(){ //你在这里做点什么 }); 但是,当我单击内部的div时,它也会触发容器的click事件,因为div在容器内部,所以,我需要一种方法来防止在单击内部div时触发容器事件 非常感谢 将单击事件处理程序添加到内部,如下所示: <div class="container"> <div class="inside">I am not fire when click me</div>

例如


单击我时,我不是火
$('.container')。单击(函数(){
//你在这里做点什么
});
但是,当我单击内部的div时,它也会触发容器的click事件,因为div在容器内部,所以,我需要一种方法来防止在单击内部div时触发容器事件


非常感谢

将单击事件处理程序添加到内部,如下所示:

<div class="container">
  <div class="inside">I am not fire when click me</div>
</div>

$('.container').click(function(){
  // container do something here
});
或者,
event.stopPropagation()
也可以像这样防止冒泡:

$('.inside').click(function(event) {
    // do anything you might want with the click for inside
    return false; // prevents click event from bubbling up the DOM hierarchy
});
解释事件冒泡

$('.inside').click(function(event) {
    // do anything you might want with the click for inside
    event.stopPropagation(); // prevents click event from bubbling up the DOM hierarchy
});
那应该对你有用。它会阻止内部div中的任何单击冒泡到容器


这里还有一个简单的示例-

作为更通用的解决方案,您应该签入
容器
单击
事件处理程序

$('.inside').click(function(e) {
    e.stopPropagation();
});

通过这种方式,您不会阻止事件的传播,这会破坏绑定处理程序。

单击事件对我不起作用,而mousedown事件可以正常工作,但当我拖动并移动内部div[Dragable plugin applied]时,容器事件触发器again@qinHaiXiang-您是否检查并查看事件到达容器时的目标是什么,如中所述?是inside div还是container div?否。
stopPropagation()
通常是个坏主意,尤其是在这种情况下,这样做是错误的:回答很好!非常感谢。
$('.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
});