jquery取消事件冒泡的三种方法展示

jquery取消事件冒泡的三种方法展示

html代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>阻止冒泡</title>
<script src="C:\Users\Administrator\Desktop\jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
    // 为span元素绑定click事件
    $('span').bind("click",function(event){
        var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";//获取html信息
        $('#msg').html(txt);// 设置html信息
    });
    // 为div元素绑定click事件
    $('#content').bind("click",function(event){
        var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>";
        $('#msg').html(txt);
    });
    // 为body元素绑定click事件
    $("body").bind("click",function(){
        var txt = $('#msg').html() + "<p>body元素被点击.<p/>";
        $('#msg').html(txt);
    });
})
</script>
</head>
<body>

问题一:当我们点击“span”时会触发“div”和“body”的事件,如何只触发单一点击事件不触发到父节点点击事件呢?修改:在各点击事件结尾加上stopPropagation()会阻止触发上一节点事件;
修改如下:


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="C:\Users\Administrator\Desktop\jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
    // 为span元素绑定click事件
    $('span').bind("click",function(event){
        var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";//获取html信息
        $('#msg').html(txt);// 设置html信息
		event.stopPropagation()
    });
    // 为div元素绑定click事件
    $('#content').bind("click",function(event){
        var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>";
        $('#msg').html(txt);
		event.stopPropagation()
    });
    // 为body元素绑定click事件
    $("body").bind("click",function(){
        var txt = $('#msg').html() + "<p>body元素被点击.<p/>";
        $('#msg').html(txt);
    });
})
</script>
</head>

<body>
<div id="content"> 外层div元素 <span>内层span元素</span> 外层div元素 </div>

<div id="msg"></div>
</body>
</html>

问题二:表单没有通过验证阻止表单提交,这时候可以通过设置event.preventDefault(); 阻止默认行为 ( 表单提交 )。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="C:\Users\Administrator\Desktop\jquery-3.1.1.min.js"></script>

<script>
$(function(event){
	$("form").submit(function(){
		if($("input[name='username']").val()==''){
			event.preventDefault();
			$("#msg").html("<p>文本框的值不能为空.</p>");
					alert("123")
			}
		})
	})
	
</script>
</head>

<body>

<form action="www.baidu.com">
	<input name="username">
	<input type="submit" value="提交">
</form>
<div id="msg"></div>
</body>
</html>

第三种阻止冒泡方式 return false:实际上这个很通用但是内部是执行了 (1)event.preventDefault();
(2)event.stopPropagation();
(3)停止回调函数执行并立即返回;这三个动作我们需要根据实际情况选择阻止冒泡的方式

猜你喜欢

转载自1197581932.iteye.com/blog/2353256