简体   繁体   English

jQuery 不是选择器不起作用

[英]jQuery not selectors not working

I have a problem with jQuery selectors:我有 jQuery 选择器的问题:

$("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") .在该代码中,如果我删除.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.我使用live是因为通常元素是通过.append()添加的,除了一些元素。 This is an example: http://jsfiddle.net/88w8N/ .这是一个例子: 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.基本上我想处理对 li 元素的点击,但如果它点击.title.content div 则.title What I'm doing wrong?我做错了什么? Thanks!谢谢!

You need to stop jQuery from triggering an event attached to the parent when the child is triggered .您需要阻止 jQuery 在触发子级时触发附加到父级的事件

You need to use jQuery's event.stopPropagation() function, which你需要使用 jQuery 的event.stopPropagation()函数,它

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.防止事件在 DOM 树中冒泡,从而防止任何父处理程序收到该事件的通知。

In your code specifically: http://jsfiddle.net/88w8N/21/具体在您的代码中: 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/要解决您的“实时”问题,请尝试以下修改: 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/

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

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