jQuery Click Event On Div, Except Child Div

2019-03-12 04:22发布

I have the following 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. 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. How can make the entire div server have the click event except the delete-server div.

4条回答
祖国的老花朵
2楼-- · 2019-03-12 04:59

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.

查看更多
淡お忘
3楼-- · 2019-03-12 05:13

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

查看更多
在下西门庆
4楼-- · 2019-03-12 05:15

Only this works for me.

js_object is jQuery object for meta parent like a $('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

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
});
查看更多
欢心
5楼-- · 2019-03-12 05:18
$(".server").on('click', ':not(.delete-server)', function (e) {
     e.stopPropagation()
     // Show edit dialog
});

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

查看更多
登录 后发表回答