event.stopPropagation()和event.preventDefault()

1.event.preventDefault()

preventDefault() 方法阻止元素发生默认的行为(例如,当点击提交按钮时阻止对表单的提交)

2.event.stopPropagation()

event.stopPropagation() 方法阻止事件冒泡到父元素,阻止任何父事件处理程序被执行。尤其是点击事件。

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("span").click(function(event){
    event.stopPropagation();
    alert("The span element was clicked.");
  });
  $("p").click(function(event){
    alert("The p element was clicked.");
  });
  $("div").click(function(){
    alert("The div element was clicked.");
  });
});
</script>
</head>
<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><span style="background-color:orange">This is a span element in the p
	and the div element.</span></p></div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_36836277/article/details/88692137