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.

回答1:

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

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



回答2:

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



回答3:

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.



回答4:

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
});