2011-11-07 68 views
2

可能重复:
Prevent click event from affecting parent jqueryjQuery的点击忽略父点击

我有一个类似的DOM结构:

<div class="parent"> 
    <div class="child"> 

    </div> 
</div> 

我有以下的jQuery :

$('.parent').click(function(){ 
    $(this).hide(); 
}); 

当点击.child我不希望父母隐藏,但很明显,因为.child.parent这个自然发生的孩子。我试着加入:

$('.child').click(function(e){ 
    e.stopPropagation(); 
}); 

但它仍然无法正常工作。我也尝试用return false;替换e.stopPropagation

有什么建议吗?

JSFiddle

+4

Hunderds的重复。让我找一个。 –

+0

真的好友,你一直在这里等5个月?你应该已经知道如何搜索。 –

+0

我试过搜索,但没有解决方案。我将把我的代码放到jsfiddle中,这样你就可以看到自己 –

回答

3

这绝对作品看我的代码的fiddle。尝试点击绿色的div。如果它不适用于您的网站,那么您还有其他问题。

+0

hmmmm,任何想法为什么它不能在我的小提琴中工作? http://jsfiddle.net/mPUTe/ –

+1

更新了你的[小提琴](http://jsfiddle.net/mPUTe/2/)。您的问题是,当元素尚不存在时,您正在绑定点击事件。或者,您可以使用现场活动 – topek

1

好的,这里的解决方案:小提琴:http://jsfiddle.net/mPUTe/1/
不要将事件侦听器绑定到.pu_container。请检查e.target.pu_bg点击监听器是否有pu_container类。如果是,返回。

(function($) { 
    $.fn.show = function() { 
     return this.each(function() { 
      var link = $(this); 
      link.click(function(e) { 
       $('body').append('<div class="pu_bg">'); 
       $('.pu_bg').css({ 
        'opacity': 0.5 
       }).on('click', function(e) { 
        if($(e.target).hasClass('pu_container')) return; //<--Magic? 
        $(this).fadeOut(function(){ 
         $(this).remove();  
        }); 
       });; 
       $('.pu_bg').append('<div class="pu_container">'); 
       e.preventDefault(); 
      }); 
     }); 
    }; 
})(jQuery);