如何停止调用父绑定?
例子:
<div id="test">
<a href="#" id="link" onclick="alert('testing')">TEST</a>
</div>
$('#test').on('click',function(){
alert('I dont want it to fire it up!');
})
如果我单击#link,我只想触发#link 中的onclick,而不是#test 上的事件
感谢您的回复
event.stopPropagation();
return false在您的事件处理程序中执行 a将防止传播。不幸的是,它也会阻止链接的默认行为;例如,在您的情况下加载<page url here>#:
<a href="#" id="link" onclick="alert('testing'); return false;">TEST</a>
jQuery.event对象包含一个有趣的属性,在冒泡事件的情况下,该属性target将包含接收到实际点击的元素。如果有意义,您可以使用它:
$('#test').on('click', function(e) {
if ($(e.target).is("#link")) {
alert('#link was clicked; comment out this alert to ignore it');
}
else {
alert('you clicked me but you did not click #link');
}
});
顺便说一句,我想知道混合内联和无障碍事件处理程序是否有理由?
stopPropagation()防止事件传播。但是,您必须将事件传递给事件处理程序才能执行此操作。
$('#test').on('click',function(e){
e.stopPropagation();
})
stopPropagation() 是 jQuery 内外的有效 javascript 函数。jQuery 有助于支持 IE,但您也可以只使用 cancelBubble 来支持 IE。
document.getElementById('link').onclick = function(e) {
if (e && e.stopPropagation) e.stopPropagation(); else window.event.cancelBubble = true;
}