我对 jQuery 选择器有疑问:
$("ul.questions li").not(".title, .content").click().live('click', function(){
$(".inspector").slideToggle();
if($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
});
在该代码中,如果我删除 .not(".title, .content")
,它就会起作用。但如果我添加它,它就不会得到点击。我使用 live
因为通常元素是通过 .append()
添加的,除了某些元素。这是一个示例:http://jsfiddle.net/88w8N/ 。基本上我想处理对 li 元素的点击,但如果它点击 .title
和 .content
div,则不处理。我做错了什么?谢谢!
最佳答案
您需要stop jQuery from triggering an event attached to the parent when the child is triggered .
您需要使用 jQuery 的 event.stopPropagation()
函数,其中
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
具体在您的代码中:http://jsfiddle.net/88w8N/21/
$("ul.questionssel li div, ul.questionsnosel li div").on('click', function(e) {
e.stopPropagation();
});
更新
要解决您的“实时”问题,请尝试以下修改: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();
});
关于javascript - jQuery 不选择器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8726094/