2014-10-11 113 views
0

我有一个父DIV与背景图像,当你mouseover它淡入在右上角的小图标(小孩div),小图标是可点击的,父母div(具有背景图像)也是可点击的。jquery防止点击父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(); 
        } 
        );   
}); 

回答

2

这就是所谓的 '事件传播' 或更常见的 '事件冒泡'。

该解决方案可以发现here

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

你订正工作jsfiddle

+0

啊!感谢您的解释和代码!将接受你的答案,因为时间用完:) – Ryan 2014-10-11 03:06:45

+0

快速问题:是否有可能在儿童DIV中使用href? (而不是使用JQuery的onClick,目前附加到子div) – Ryan 2014-10-11 03:09:37

+0

@Ryan它应该在理论上工作,但我想知道是否因为它包裹在jQuery的'click'事件中,这在某种程度上被覆盖了......我没有没有具体处理。也许在这里快速搜索SO可以为您提供答案。对不起,我不知道我的头顶。 – SnareChops 2014-10-11 03:13:48