首页 文章

Jquery阻止onClick为父DIV触发[重复]

提问于
浏览
0

这个问题在这里已有答案:

我有一个带有背景图像的父DIV,当你将它鼠标悬停在右上角时(小孩div),小图标是可点击的,而父div(具有背景图像)也是可点击的 .

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

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

Working fiddle is here: 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();
                    }
                   );        
});

1 回答

  • 2

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

    解决方案可以找到here

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

    你修改过的工作jsfiddle

相关问题