如何在JQuery中的容器内单击元素时取消容器div触发的点击事件? [英] How to cancel click event of container div trigger when click elements which inside container in JQuery?

查看:131
本文介绍了如何在JQuery中的容器内单击元素时取消容器div触发的点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

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

$('.container').click(function(){
  // container do something here
});

但是,当我点击里面的div也会触发容器的点击事件,因为div在容器,所以,我需要一种方法来防止容器事件触发,当我点击里面的div!

but,when I click the div inside it also trigger the container's click event because the div is inside the container, so , I need a way to prevent the container event trigger when I click on the inside div!

非常感谢!

推荐答案

作为一个更通用的解决方案,您应该检查 c $ e.target c $ c>事件处理程序。

As a more general solution, you should check e.target in container's click event handler.

$('.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
});

这样你就不会阻止事件的传播,这将破坏绑定 live 处理程序。

This way you're not preventing propagation of the event, which would break bound live handlers.

这篇关于如何在JQuery中的容器内单击元素时取消容器div触发的点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆