两个OnClick事件重叠了。

8
我有一个元素嵌套在另一个元素中,当我点击下面的元素时,我希望滑块打开。当我点击最外层的元素时,我希望滑块关闭。
不幸的是,当我点击最外层的元素时,它也会点击下面的元素。有没有一种方法只在最外层元素上单击,忽略下面元素的点击?事件在单击时触发并用JavaScript执行。
我尝试使用z-index,但它仍会捕获下面元素的点击,并且因为功能相反,所以什么也不会发生。
编辑:根据“代码胜过1000言”的提示
var $target = $(this).data('pos', i) //give each li an index #
    $target.data('hpaneloffsetw', $target.find('.hpanel:eq(0)').outerWidth()) //get offset width of each .hpanel DIV (config.dimensions.fullw + any DIV padding)
    $target[haccordion.ismobile? "click" : "mouseenter"](function(){
        haccordion.expandli(config.accordionid, this)
        config.$lastexpanded=$(this)
    })

    if (config.collapsecurrent){ //if previous content should be contracted when expanding current
        $('.close').click(function(){
            $target.stop().animate({width:config.paneldimensions.peekw}, config.speed) //contract previous content
        })
        $target.dblclick(function(){
            $(this).stop().animate({width:config.paneldimensions.peekw}, config.speed) //contract previous content
        })
    }

因为这段代码是借来的,我对它的理解不是很多。但基本上我想让"click": "mousteenter"函数在点击时起作用,而不会干扰到.close().click。


6
代码胜过一万言,尽管听起来你需要在点击处理程序中使用event.stopPropagation - Rory McCrossan
尝试使用Delegate https://api.jquery.com/delegate/? - Se0ng11
尝试使用 e.stopPropagation(); - Sandy
@Sandy:你的评论和Rory上面的评论有什么不同? - Abhitalks
抱歉,我没有注意到他说了同样的事情。 - Sandy
1
谢谢Rory和Sandy,event.stopPropagation();解决了问题! - hahaha
4个回答

14

看起来你需要阻止点击事件冒泡到父级元素被捕获。你可以使用 stopPropagation() 来实现:

$('.close').click(function(e) {
    e.stopPropagation();
    $target.stop().animate({ width: config.paneldimensions.peekw }, config.speed);
})
$target.dblclick(function(e) {
    e.stopPropagation();
    $(this).stop().animate({ width: config.paneldimensions.peekw }, config.speed);
})

谢谢!这个方法有效,解释清晰,说明了为什么会出现这种情况以及如何解决。 - hahaha
嗯,我知道已经晚了几天,在Chrome上运行得很好,但在Firefox上不行,是Firefox不支持stopPropagation()还是它更挑剔一些? - hahaha
Firefox支持stopPropagation()。为什么它不起作用?您的控制台中有任何错误吗? - Rory McCrossan
stopPropagation()行上只是返回了"ReferenceError: event is not defined" - hahaha
你是否将 event 传递给了点击处理程序?请注意我示例中的 (e) 部分。 - Rory McCrossan
既然你提到了,我有event.stopPropagation();,但是当我使用ctr-f查找event时,只发现了一个实例。(不过为什么它在Chrome上能正常工作呢) - hahaha

1
尝试以下 fiddle
$("#outer").click(function(){alert("outer clicked")});
$("#inner").click(function(e){
    alert("inner clicked")
    e.stopPropagation();
});

0
使用CSS特定的jQuery指向精确元素,例如下面的例子,使用>指向精确的子元素。
table > tbody > tr > td > input[type='text'] 

像这样。


0

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