两个事件处理程序都附加到
body
元素。和文档
event.stopPropagation()
说:
请注意,这不会阻止
相同的
元素。
从那时起
stopPropagation
不会阻止对同一元素执行处理程序,它会防止进一步传播到其他元素。
如果即使同一元素上的所有其他事件处理程序都不应再执行,则需要
event.stopImmediatePropagation()
:
描述:保持其余处理程序不被执行,并防止事件在DOM树上冒泡。
$("body").on('click', ".application-checkbox", function(e) {
alert('checkbox');
e.stopImmediatePropagation();
});
$('body').on('click', "tr", function(e) {
alert('row');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<div class="ckbox">
<input type="checkbox" class="application-checkbox" id="checkbox">
<label for="checkbox">label</label>
</div>
</td>
<td></td>
</tr>
</table>
但该方法的问题在于,回调是按照附加顺序调用的,因此如果
tr
在
.application-checkbox
它不起作用。
因此,您需要修复该问题,或者需要将事件侦听器附加到DOM的不同级别:
$("tbody").on('click', ".application-checkbox", function(e) {
alert('checkbox');
e.stopPropagation();
});
$('table').on('click', "tr", function(e) {
alert('row');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
<div class="ckbox">
<input type="checkbox" class="application-checkbox" id="checkbox">
<label for="checkbox">label</label>
</div>
</td>
<td></td>
</tr>
</tbody>
</table>