【发布时间】:2013-12-06 01:45:47
【问题描述】:
我有一些 DIV,其他开发者将它们绑定一个点击事件名称fn_propagation。
现在我想为它们添加一个新函数,名称为fn_stoppropagation。
问题是当我在fn_stoppropagation 中调用e.stopPropagation() 时,它也会停止在fn_propagation 中的事件传播。
如何在fn_propagation 中保持事件传播,但在我添加的函数中停止传播? (我知道通过 ID 向每个 DIV 添加事件并停止使用 stopPropagation() 可以做到这一点,但我认为这不是一个好方法。)
小提琴: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,
谢谢。
【问题讨论】:
-
这正是我所期望的。为什么你认为它是错误的(除了我错了)
-
使用
'div'作为选择器的糟糕示例...肯定选择器比这更具体? -
函数不冒泡,事件冒泡。从任何处理程序停止事件都会停止它。不能同时冒泡和不冒泡。
-
@charlietfl:我认为 OP 这样做是为了将处理程序分配给所有嵌套元素以进行说明。
标签: javascript jquery stoppropagation