zoukankan      html  css  js  c++  java
  • 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();
            });

  • 相关阅读:
    纪念一下なぞなぞゲーム
    071221 晴
    Sightseeing Cows poj3621
    【HDU 5721】Palace(平面最近点对)
    继承和多态的一些知识点
    3D Convex Hull HDU 3662 三维凸包
    Monthly Expense POJ 3273 二分
    确定比赛名次 HDU 1285拓扑排序裸题
    序列变换
    Dropping tests 二分+01分数规划
  • 原文地址:https://www.cnblogs.com/bky-1083/p/6353975.html
Copyright © 2011-2022 走看看