jQuery事件对象的属性和方法详解

2020-05-23 06:23:34易采站长站整理

</div>
<br />
<div id="msg"></div>
</div>
<script type="text/javascript">
//为 <span> 元素绑定 click 事件
$("span").click(function() {
$("#msg").html($("#msg").html() + "<p>内层span元素被单击</p>");
});
//为 Id 为 content 的 <div> 元素绑定 click 事件
$("#content").click(function(event) {
$("#msg").html($("#msg").html() + "<p>外层div元素被单击</p>");
event.stopPropagation(); //阻止事件冒泡
});
//为 <body> 元素绑定 click 事件
$("body").click(function() {
$("#msg").html($("#msg").html() + "<p>body元素被单击</p>");
});
</script>
</body>

</html>

点击span冒泡到content的点击事件,然后进入到content的click function里面执行阻止冒泡语句,也就不会冒泡到body,所以点击span不会出现body元素被点击。

$(‘#msg’).html($(‘#msg’).html()+ “<p>内层span元素被单击</p>”); //在msg原有内容上追加
$(‘#msg’).html(“<p>内层span元素被单击</p>”); //替换原来的内容