如何在使用委托时停止事件传播?
当我使用.bind绑定子对象和父对象的事件时,子事件可以通过返回false来停止事件传播; 但是当我使用委托时,返回false; 不会停止事件传播。
http://jsfiddle.net/J3EAQ/
HTML:
JS:
$('.parent').delegate('.child','click',function(e){ alert('child click'); return false; }); $('.parent').bind('click',function(e){ alert('parent click'); });
e.stopPropagation()
在这种情况下不起作用。 请改用e.stopImmediatePropagation() 。 这是一个小提琴
为什么两个点击处理程序可以有一个:
$( '.parent' ).click(function ( e ) { if ( $( e.target ).is( '.child' ) ) { alert( 'child click' ); } else { alert( 'parent click' ); } });
现场演示: http : //jsfiddle.net/J3EAQ/2/
这种模式的概括:
$( element ).click(function ( e ) { if ( e.target === this ) { // this element was clicked directly } else { // this element was NOT clicked directly // a descendant of this element was clicked } });
单独的处理程序?
$( '.parent' ).click(function ( e ) { if ( this ==== e.target ) { parentClicked.call( e.target, e ); } else { childClicked.call( e.target, e ); } }); function childClicked( e ) { // child click handler } function parentClicked( e ) { // parent click handler }
您应该使用e.stopPropagation()
来阻止传播,而不是返回false。
return false
在技术上是两件事; 1)防止默认动作,2)停止传播。 尝试切换到e
上的方法调用,看看是否能解决问题。
你总是可以使用e.stopPropagation()
对我有用的是检查点击处理程序中您不希望被其他点击事件触发的点击目标的类名。 像这样的东西。
if(e.target.className.toString().indexOf("product-row") > -1){ // Only do stuff if the correct element was clicked }
您的活动没有被传播。 您将单击处理程序绑定到.parent,并且您单击.parent