简体   繁体   中英

jQuery not selectors not working

I have a problem with jQuery selectors:

$("ul.questions li").not(".title, .content").click().live('click', function(){
        $(".inspector").slideToggle();
        if($(this).hasClass("selected")) {
               $(this).removeClass("selected");
        } else {
               $(this).addClass("selected");
        }
});

In that code it works if I remove .not(".title, .content") . but if I add it, it just doesn't gets the click. I use live because usually the elements are added through .append() , except some ones. This is an example: http://jsfiddle.net/88w8N/ . Basically I want to handle click on the li element, but not if it clicks on the .title and .content divs. What I'm doing wrong? Thanks!

You need to stop jQuery from triggering an event attached to the parent when the child is triggered .

You need to use jQuery's event.stopPropagation() function, which

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

In your code specifically: http://jsfiddle.net/88w8N/21/

$("ul.questionssel li div, ul.questionsnosel li div").on('click', function(e) {
    e.stopPropagation();
});

UPDATE

To fix your "live" issue, try the following modification: http://jsfiddle.net/88w8N/25/

$("ul.questionssel").on('click', 'li', function() {

    //$(".inspector").slideToggle();
    if($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    } else {
        $(this).addClass("selected");
    }
});

$("ul.questionsnosel").on('click', 'li', function() {
    //$(".inspector").slideToggle();
    if($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    } else {
        $(this).addClass("selected");
    }
});

$("ul.questionssel li div, ul.questionsnosel li div").on('click', function(e) {
    e.stopPropagation();
});

您可以使用 not selector 而不是 not function http://api.jquery.com/not-selector/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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