gpt4 book ai didi

javascript - 我可以停止某些功能的事件传播吗?

转载 作者:行者123 更新时间:2023-11-30 12:52:34 25 4
gpt4 key购买 nike

我有一些 DIV,其他开发人员为它们绑定(bind)了一个点击事件名称 fn_propagation

现在我想给它们添加一个新函数 fn_stoppropagation

问题是当我在 fn_stoppropagation 中调用 e.stopPropagation() 时,它也会在 fn_propagation 中停止事件传播。

如何在 fn_propagation 中保持事件传播,但在我添加的函数中停止传播? (我知道通过 ID 向每个 DIV 添加事件并停止使用 stopPropagation() 可以做到这一点,但我认为这不是一个好方法。)

fiddle :http://jsfiddle.net/android/3GurB/2/

HTML:

<div id='div1'>
<div id='div2'>
<div id='div3'>
Click Me
</div>
</div>
</div>

JS:

$('div').click(fn_propagation)      // Other developer add this event
.click(fn_stoppropagation); // What I going to add.

// I want to keep propagation of this function
function fn_propagation(){
alert('propagation '+$(this).attr('id')+' called');
$(this).toggleClass('green');
}

// But stop propagation of this function
function fn_stoppropagation(e){
alert('stoppropagation '+$(this).attr('id')+' called');
e.stopPropagation();
}

Click Me 被点击时,预期输出:

   propagation div3 called     // called
stoppropagation div3 called // called
propagation div2 called // expected, but NOT called,
propagation div1 called // expected, but NOT called,

谢谢。

最佳答案

传播发生在 DOM 中,它只能针对整个元素打开或关闭,而不是针对特定的事件处理程序。

我的建议:将当前元素与 click target 进行比较:

function fn_stoppropagation(e){
if (this===e.target) {
// the following will only run for the target, not its ancestors
alert('stoppropagation '+$(this).attr('id')+' called');
}
}

关于javascript - 我可以停止某些功能的事件传播吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com