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