jQuery点击子元素时忽略父元素的点击

7

可能是重复问题:
防止点击事件影响父级jQuery

我有一个类似于以下结构的DOM:

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

   </div>
</div>

I have the following jQuery:

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

当单击.child时,我不希望父元素隐藏,但显然由于.child.parent的子元素,这种情况自然会发生。我尝试添加以下内容:

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

但是它仍然不起作用。我也尝试将e.stopPropagation替换为return false; 有什么建议吗? JSFiddle

我尝试过搜索,但是没有一个解决方案起作用。我将把我的代码放到jsfiddle中,这样你就可以亲自看看了。 - Lee Price
2个回答

7

这肯定有效,请查看我对你代码的示例。尝试点击绿色的div,如果在您的网站上无法工作,则可能有其他问题。


你有什么想法为什么这个在我的 jsfiddle 不起作用?http://jsfiddle.net/mPUTe/ - Lee Price
1
更新了你的fiddle。你的问题是在元素还不存在时绑定了点击事件。或者你可以使用一个live事件。 - topek

2
啊,好的,这里是解决方案:Fiddle: http://jsfiddle.net/mPUTe/1/
不要将事件监听器绑定到.pu_container上。相反,检查.pu_bg点击监听器中的e.target是否具有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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接