【问题标题】:Jquery prevent onClick for parent DIV from firing [duplicate]Jquery阻止父DIV的onClick触发[重复]
【发布时间】:2014-10-11 02:56:09
【问题描述】:

我有一个带有背景图像的父 DIV,当您将鼠标悬停在其上淡入右上角的一个小图标(一个子 div)时,该小图标是可点击的,而父 div(即有背景图片)也是可点击的。

我的问题是当我点击小图标的时候,也触发了父DIV的点击事件。
当我单击小图标时,我只希望调用子 div 的 onclick。如果我可以让 href 在小图标中工作,那也是可以接受的。

(父 div:img1 和 id “momClickable”)
(带图标的子 div:topIcon1)

工作小提琴在这里: http://jsfiddle.net/auhjo9nw/

我的 HTML:

<div class="img1" id="momClickable">- img 206x206 here - 
<div class="topIcon1"><a href="#"><img src="momIcon.jpg" border="0" /></a></div>
</div>

上面的css是:

.img1 {
    width:206px;
    height:206px;
    margin-left: auto;
    margin-right: auto;
    background:url(Mom206x206.jpg);
}

.topIcon1 {
    position:relative;
    width:45px;
    left: 155px;
    top: -10px;
    display:none;
}

我的 jquery:

// To make the div clickable
$('#momClickable').click(function() {
      console.log('You clicked the DIV.');
    }); 

//To make the icon clickable
$('.topIcon1').click(function() {
      console.log('You clicked the DIV 2.');
    });     

$(function(){
    $(".pictureBoxWrapper1").hover(function(){
      $(this).find(".topIcon1").fadeIn(100);
      $('#momClickable').css('cursor','pointer');
    }
                    ,function(){
                        $(this).find(".topIcon1").fadeOut();
                    }
                   );        
});

【问题讨论】:

    标签: jquery onclick


    【解决方案1】:

    这称为“事件传播”或更常见的“事件冒泡”。

    解决办法可以在here找到

    $('.topIcon1').click(function(event) {
        console.log('You clicked the DIV 2.');
        event.stopPropagation();
    }); 
    

    你修改后的工作jsfiddle

    【讨论】:

    • 啊!感谢您的解释和代码!时间用完会接受你的回答:)
    • 快速问题:是否可以在子 DIV 中使用 href? (而不是使用当前附加到子 div 的 JQuery 的 onClick)
    • @Ryan 它理论上应该可以工作,但我想知道是否因为它被包裹在 jQuery click 事件中,所以它被某种方式覆盖了......我没有具体处理过。也许在这里快速搜索 SO 可以为您提供该答案。对不起,我不知道在我的头上。
    • 不客气,谢谢回答,已采纳。有一个好的 W/E!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 2021-06-11
    • 1970-01-01
    • 2019-12-14
    • 2016-09-14
    相关资源
    最近更新 更多