jQuery[补1]

假设网页上有两个元素,其中一个元素嵌套在另一个元素中,并且都被绑定了 click 事件,同时 body 元素上也绑定了 click 事件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="content">
    外层 div 元素
    <span>内层 span 元素</span>
    外层 div 元素
</div>
<div id="msg"></div>
<script src="../../vender/jquery-1.11.3/jquery-1.11.3.js"></script>
<script type="text/javascript">
    $(function () {
        $('span').click(function (e) {
            var txt = $('#msg').html()+"<p>内层 span 元素被单击</p>";
            $('#msg').html(txt);
        });
        $('div').click(function () {
            var txt = $('#msg').html()+"<p>外层 div 元素被单击</p>";
            $('#msg').html(txt);
        });
        $('body').click(function () {
            var txt = $('#msg').html()+"<p>body 元素被单击</p>";
            $('#msg').html(txt);
        })
    })
</script>
</body>
</html>

当单击内部 span 元素,会输出三条记录:

该现象就是由事件冒泡引起的。

元素的 click 事件会按照以下顺序冒泡:

  • span
  • div
  • body

其顺序与事件捕获相反。

停止事件冒泡可以阻止事件中其他对象的事件处理函数被执行,在 jQuery 中提供stopPropagation()方法来停止冒泡。

$('span').click(function (e) {
            var txt = $('#msg').html()+"<p>内层 span 元素被单击</p>";
            $('#msg').html(txt);
            e.stopPropagation();
        });

原文地址:https://www.cnblogs.com/bky-1083/p/6353975.html