JQuery use .on() with not selector

2019-02-21 12:41发布

I am using .on() function with this syntax:

$(".schemaTab").on("click", ".schema", function () {})

instead of .live() because I am adding .schema divs dynamically. Those divs have this code:

<div class="schema" id="SCH_16">
   <img src="Img/btnRemove.png" class="ikona SCH_Remove" alt="Smazat" title="Smazat">
</div>

But I need to exclude the img from click event of its parent div, so any idea how to do it?

I tried:

$(".schemaTab").not(".SCH_Remove").on("click", ".schema", function () {})

...but it didn't work and I don't know how to add the .not() inside the .on() code

4条回答
神经病院院长
2楼-- · 2019-02-21 12:55

The whole point of doing this is to handle events on elements not yet in the DOM, which includes your .sch_Remove.

$(".schemaTab").on("click", ".schema", function () {})

In order to prevent the parent click action from being triggered when that img is clicked, add the following (in addition to your function above).

$(".schemaTab").on("click", ".SCH_Remove", function () { return false; })

This will prevent the 'click' event from propagating to the parent and triggering its onclick method and prevent the default click behavior.

查看更多
beautiful°
3楼-- · 2019-02-21 12:56

I just ran into this problem and used the :not selector, like this:

$('.schemaTab').on('click', '.schema:not(.booga)', function(event) {
  // Fun happens here
});

I'm using jQuery 1.11.0, I don't know how far back this works.

查看更多
做个烂人
4楼-- · 2019-02-21 13:08

.not() won't work because on method attaches event handlers to the currently selected set of elements in the jQuery object and uses the original selector to test whether the event should apply.

So I reckon selecting and then filtering in your case will do the trick.

API: http://api.jquery.com/on/

you could try this:

$(".schemaTab").on("click", ".schema", function (e) {

    if (!$(e.target).is(".schemaTab")) {
         // not stuff in here
    }

});
查看更多
趁早两清
5楼-- · 2019-02-21 13:09

Just make sure the target matches:

$('.schemaTab').on('click', '.schema', function(e) {
    if(!$(e.target).is('.schema')) {
        return;
    }

    // Do stuff
});
查看更多
登录 后发表回答