Javascript Div上的jQuery点击事件,除了子Div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10160219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:07:11  来源:igfitidea点击:

jQuery Click Event On Div, Except Child Div

javascriptjqueryonclick

提问by Justin

I have the following HTML:

我有以下 HTML:

<div class="server" id="32">
  <a>Server Name</a>
  <div class="delete-server">X</div>
</div>

I am trying to make it so when users click the serverdiv it brings up an edit dialog. The problem is simply doing:

我试图做到这一点,当用户单击serverdiv 时,它会显示一个编辑对话框。问题只是在做:

 $(".server").click(function () {
     //Show edit dialog
 });

Does not work, because if they click the X which is delete, it brings up the edit dialog. How can make the entire div serverhave the click event except the delete-serverdiv.

不起作用,因为如果他们单击要删除的 X,则会弹出编辑对话框。如何让整个 divserver具有除delete-serverdiv之外的点击事件。

回答by Joseph Silber

$(".server").on('click', ':not(.delete-server)', function (e) {
     e.stopPropagation()
     // Show edit dialog
});

Here's the fiddle: http://jsfiddle.net/9bzmz/3/

这是小提琴:http: //jsfiddle.net/9bzmz/3/

回答by gdoron is supporting Monica

Just check what is the element who triggered the event:

只需检查触发事件的元素是什么:

$(".server").click(function(e) {
    if (!$(e.target).hasClass('delete-server')) {
        alert('Show dialog!');
    }
});?

LIVE DEMO

现场演示

回答by Tomalak

There is an alternative way to solve this:

有一种替代方法可以解决这个问题:

$(".server").click(function () {
    // show edit dialog
});
$(".delete-server").click(function (event) {
    // show delete dialog for $(this).closest(".server")
    event.stopPropagation();
});

Just make sure a click event issued on .delete-serverdoes not bubble up to the parent element.

只要确保发出的点击事件.delete-server不会冒泡到父元素。

回答by German Khokhlov

Only this works for me.

只有这对我有用。

js_objectis jQuery object for meta parent like a $('body')

js_object是元父级的 jQuery 对象,例如 $('body')

jq_object.on('click', '.js-parent :not(.js-child-1, .js-child-2)', function(event) {
    //your code
});

jq_object.on('click', '.js-child-1', function(event) {
    //your code
});

jq_object.on('click', '.js-child-2', function(event) {
    //your code
});

Fore your case:

Fore你的情况:

server — js-parent

服务器 — js-parent

delete-server — js-child-1

删除服务器 — js-child-1

jq_object.on('click', '.server :not(.delete-server)', function(event) {
    //your code
});

jq_object.on('click', '.delete-server', function(event) {
    //your code
});