简体   繁体   English

jQuery Click Div On Div,除了Child Div

[英]jQuery Click Event On Div, Except Child Div

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 server div it brings up an edit dialog. 我试图这样做,当用户点击server div它会打开一个编辑对话框。 The problem is simply doing: 问题只是做:

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

Does not work, because if they click the X which is delete, it brings up the edit dialog. 不起作用,因为如果他们点击删除的X,它会打开编辑对话框。 How can make the entire div server have the click event except the delete-server div. 如何使整个div server具有除delete-server div之外的click事件。

$(".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/

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 现场演示

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-server does not bubble up to the parent element. 只需确保.delete-server上发出的click事件不会冒泡到父元素。

Only this works for me. 只有这对我有用。

js_object is 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: 在你的情况下:

server — js-parent 服务器 - js-parent

delete-server — js-child-1 delete-server - 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM