event.stopPropagation() 方法阻止事件冒泡到父元素,阻止任何父事件处理程序被执行。
在绑定的事件中使用阻止事件冒泡:
$("p").click(function(event){
alert("The p element was clicked.");
});
以下是示例
<script>
$(document).ready(function(){
$("p").click(function(event){
event.stopPropagation();
alert("The p element was clicked.");
});
$("div").click(function(){
alert("The div element was clicked.");
});
});
</script>
<body>
<div style="height:100px;width:500px;padding:10px;border:1px solid blue;background-color:lightblue;">
This is a div element.
<p style="background-color:pink">This is a p element, in the div element. <br></p>
</div>
</body>
在元素中写绑定事件
<input type="text" onclick="clickInput(this,1)" id="input1" class=""/>
//此时要用this来转换成上面的e
function clickInput(target,id){
var e=window.event || arguments.callee.caller.arguments[0];
e.preventDefault();
e.stopPropagation();
console.log(id)
}
- 绑定的事件需要统一,如果一个使用onfocus,另一个使用onclick,则不会阻止事件冒泡
- 阻止事件冒泡兼容ie8
function clickInput(target,id){
var e=window.event || arguments.callee.caller.arguments[0];
if ( e && e.stopPropagation ) {
// 因此它支持W3C的stopPropagation()方法
e.stopPropagation();
} else {
// 否则,我们需要使用IE的方式来取消事件冒泡
window.event.cancelBubble = true;
}
}
网友评论