0

所以我有一个父 div,里面有不同的元素。现在我已经设置好了,所以当点击父 div 时,它会应用一个“选定的”css 属性(只是突出显示它)。但是,此 div 中有一个锚标记,如果单击锚点,我不希望 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);
    }
});

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

4

3 回答 3

2

您可以在http://api.jquery.com/event.stopPropagation/中对 $('.childElement').click(function(e){ e.stopPropagation(); }) 等子元​​素使用 stopPropogation() ; 以防止单击事件传播到父元素。您还可以按照此处http://api.jquery.com/event.target/的描述检查 event.target 属性

于 2013-07-06T02:40:00.260 回答
1

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

捕获事件并使用event.stopPropagation

$(document).on('click', "a", function(event){
  event.stopPropagation();
}); 
于 2013-07-06T02:36:13.137 回答
1

我会假设我理解你的问题,所以这就是我可能会做的事情:

$(document).on("click", ".playlist-row", function(e) {
    if (!$(e.currentTarget).is("a")) {
        selectSongInPlaylist($(this));
    }
}
于 2013-07-06T02:38:18.697 回答