Jquery阻止onClick攻击父DIV

时间:2014-10-11 02:56:10

标签: jquery onclick

我有一个带有背景图像的父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();
                    }
                   );        
});

1 个答案:

答案 0 :(得分:2)

这被称为&#39;事件传播&#39;或更常见的事件冒泡&#39;。

可以找到解决方案here

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

您的修订工作jsfiddle