event.stopPropagation();阻止事件冒泡
event.preventDefault();阻止默认行为
同时阻止 事件冒泡和默认行为
return false
eg:阻止事件冒泡
<script type="text/javascript"> $(function() { //为 <span> 元素绑定 click 事件 $("span").click(function() { $("#msg").html($("#msg").html() + "<p>内层span元素被单击</p>"); }); //为 Id 为 content 的 <div> 元素绑定 click 事件 $("#content").click(function() { $("#msg").html($("#msg").html() + "<p>外层div元素被单击</p>"); }); //为 <body> 元素绑定 click 事件 $("body").click(function() { $("#msg").html($("#msg").html() + "<p>body元素被单击</p>"); }); }); </script>
<!--css-->
<style>
#content{
background:#0f0;
}
</style>
<div id="content">
外层div<br/>
<span style="background:red;">内层span</span><br/>
外层div元素
</div>
<div id="msg">
//为 <span> 元素绑定 click 事件 $("span").click(function(event) { //为方法添加一个事件对象参数 $("#msg").html($("#msg").html() + "<p>内层span元素被单击</p>"); event.stopPropagation(); //阻止 <span> 的 click 事件冒泡 });
阻止默认行为
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function() {
$(":submit").click(function(event) { //为方法添加一个事件对象参数
//当未输入用户名时,提示并阻止提交
if ($(":text").val() == "") {
$("#msg").text("用户名不能为空");
event.preventDefault(); //阻止提交按钮的默认行为(提交表单)
}
});
});
</script>
</head>
<!-- HTML -->
<body>
<form action="register.action">
用户名<input type="text" name="id" />
<input type="submit" value="注册" />
<div id="msg"></div>
</form>
</body>
</html>
阻止默认行为 和冒泡事件 同时进行
$(":submit").click(function(event) { //为方法添加一个事件对象参数
//当未输入用户名时,提示并阻止提交
if ($(":text").val() == "") {
$("#msg").text("用户名不能为空");
return false; //阻止提交按钮的默认行为(提交表单)和事件冒泡
}
});
$("span").click(function(event) { //为方法添加一个事件对象参数
$("#msg").html($("#msg").html() + "<p>内层span元素被单击</p>");
return false; //阻止 <span> 的 click 事件冒泡和默认行为(此元素没有默认行为)
});