冒泡事件与事件委托

事件发生:任何一次操作,都会产生相应的事件
事件监听:程序中是写了代码对关注事件进行捕捉和处理


冒泡事件:子元素触发的事件会向上传递,如果父类有监听同类型事件,会被激活

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>冒泡事件</title>
    <style>
        .red{
            width: 400px;
            height: 400px;
            margin: 10px;
            background-color: red;
        }
        .green{
            width: 300px;
            height: 300px;
            background-color: green;
        }
        .blue{
            width: 200px;
            height: 200px;
            background-color:blue;
        }
    </style>
    <script src="../js/jquery-1.12.4.min.js"></script>
    <script>
        $(function(){
            $('.blue').click(function(){
                alert('blue');
            });

            $('.green').click(function(){
                alert('green');
            });

            $('.red').click(function(){
                alert('red');
            });

            $(window).click(function(){
                alert('window');
            });

        })

    </script>
</head>
<body>
    <div class="red">
        <div class="green">
            <div class="blue">
            </div>
        </div>
    </div>    
</body>
</html>

效果如下:
事件冒泡:子元素事件向上传递
点击蓝色方块--->绿色-->红色-->window
冒泡事件与事件委托


事件委托:利用冒泡原理,把一些事件集中处理
jquery中使用delegate方法:
使用样列:
$('获取父类元素').delegate('子元素','事件',function(){
})

<head>
<title>jquery事件的委托</title>
    <script src="../js/jquery-1.12.4.min.js"></script>
    <script>
        $(function(){
            // 事件委托使用delegate, 将子元素事件委托给父类元素处理
            // 好处是我们不需要循环绑定每一个子元素事件.提升性能
            $('.list').delegate('li','click',function(){

                $(this).css({'color':'red'})
            })

        })
    </script>
</head>
<body>
    <ul class="list">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
</body>

猜你喜欢

转载自blog.51cto.com/10412806/2114762