简体   繁体   中英

JQuery selectors: Apply rule to element when certain child is NOT clicked

So I have a parent div with different elements inside. Right now I have it set up so when that parent div is clicked, it applies a "selected" css attribute (just highlights it). However, there is an anchor tag inside this div and I don't want the div to highlight if the anchor is clicked.

My code to highlight the div

$(document).on("click",".playlist-row",function() {
        var selected = $(this);
        highlight(selected);
});

Ideally, I want it to behave like this: (just pseudo code)

$(document).on("click",".playlist-row",function() {
    var selected = $(this);
    if ($(".childElement) is not the part clicked) {
        selectSongInPlaylist(selected);
    }
});

Any elegant ways to get something like this to work?

You could use stopPropogation() as in http://api.jquery.com/event.stopPropagation/ on the child elements like $('.childElement').click(function(e){ e.stopPropagation(); }); to prevent the click event propagating to the parent element. You could also check the event.target property as described here http://api.jquery.com/event.target/

you need to prevent the click event bubbling up to the container

capture the event and use event.stopPropagation

$(document).on('click', "a", function(event){
  event.stopPropagation();
}); 

I will assume that I understood your question, so here's what I would probably do:

$(document).on("click", ".playlist-row", function(e) {
    if (!$(e.currentTarget).is("a")) {
        selectSongInPlaylist($(this));
    }
}

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