click嵌套问题详解

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    .box{
        width: 100px;
        height: 100px;
        background: #ccc;
    }
    .one{
        width: 100px;
        height: 100px;
        background: blueviolet;
        color:#fff;
    }
</style>
<body>
<div class="box">

</div>
<div class="one">132</div>
</body>
<script src="jquery-2.1.3.min.js"></script>
<script>
    /* query的on与addEventListener是附加式的绑定事件,可以对同一个事件同时绑定多个事件处理函数,
       $("#btn").on()或btn.addEventListener()执行几次就会同时绑定几个事件处理函数。
       而用原生的onclick绑定事件其实是赋值操作,onclick中只能保留一个值,再次对onclick赋值会覆盖上次的值。*/


    //jq会有多次触发的结果
    /*$('.box').click(function () {
        console.log(1);
        $('.one').click(function () {
            console.log(2)
        })
    })*/

    //原生不会有多次触发
    /*document.querySelector('.box').onclick=function(){
        console.log(1);
        document.querySelector('.one').onclick=function(){
            console.log(2)
        }
    }*/

    //原生使用addEventListener也会有多次触发
    document.querySelector('.box').addEventListener('click',function() {
        console.log(1);
        document.querySelector('.one').addEventListener('click',function () {
            console.log(2)
        })
    })

</script>
</html>

**query的on与addEventListener是附加式的绑定事件,可以对同一个事件同时绑定多个事件处理函数, $("#btn").on()或btn.addEventListener()执行几次就会同时绑定几个事件处理函数。 而用原生的onclick绑定事件其实是赋值操作,onclick中只能保留一个值,再次对onclick赋值会覆盖上次的值。**

猜你喜欢

转载自blog.csdn.net/ddwddw4/article/details/82898349
今日推荐