JQuery选择器:当未单击某个子项时,将规则应用于元素

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

本文关键字:规则 元素 应用于 选择器 单击 JQuery      更新时间:2023-09-26

所以我有一个父div,里面有不同的元素。现在我已经设置好了,所以当单击父div时,它会应用一个"选定"的css属性(只是高亮显示它)。但是,这个div中有一个anchor标记,如果单击了anchor,我不希望div高亮显示。

我的代码突出显示div

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

理想情况下,我希望它的行为如下:(只是伪代码)

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

有什么优雅的方法可以让这样的东西发挥作用吗?

您可以使用stopPropagation()http://api.jquery.com/event.stopPropagation/在子元素上,如$(".childElement")。单击(函数(e){e.停止传播();});以防止单击事件传播到父元素。您也可以检查event.target属性,如下所述http://api.jquery.com/event.target/

您需要防止点击事件冒泡到容器

捕获事件并使用event.stop传播

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

我假设我理解你的问题,所以我可能会这样做:

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