JS阻止事件冒泡的几种方式
- 事件委托
将元素的绑定事件写起其父元素上,防止事件冒泡
<div id="parent">
<div id="son"></div>
</div>
$("#son").click(function(){
});
$("#parent").on('click','#son', function(){
});
- off()解绑
有时候,给动态生成的元素绑定事件时,会多次执行绑定的事件,这时,我们可以在元素绑定前,先off()所绑定的事件
$(selector).off('click').click(function(){
});
- event.stopPropagation();
可以阻止事件冒泡,阻止父级元素的绑定事件
<div id="parent">
<div id="son">i am son</div>
</div>
$('parent').click(function(){
alert('parent');
});
$('son').click(function(event){
alert('son');
event.stopPropagation();
/**
* 加上这句话,当点击son元素时,只会弹出son的弹窗
* 不加上这句话,点击son元素,会先弹出son,再弹出parent
*/
})
- event.preventDefault()
不会阻止事件,但会阻止事件的默认行为
<a href="//baidu.com"><button>click</button></a>
/**
* 会先弹出b,在弹出a的弹窗,但是不会跳转页面
* 去掉这句话,会先弹出b,在弹出a的弹窗,之后会跳转页面
*/
$('button').click(function(){
alert('b');
event.preventDefault();
});
$('a').click(function(){
alert('a');
})