原生的委托事件

这里简单记录一下,方便以后查阅

    <style>
        ul>li {
            width: 100%;
            height: 30px;
            margin-top: 10px;
            background-color: blue;
        }

        .active {
            background-color: #ffcd42;
        }
    </style>
</head>

<body>
    <ul id="ul">
        <li class="active"></li>
        <li></li>
    </ul>
    <button id="add">添加li标签</button>
</body>
<script>
    window.onload = function () {
        //按钮添加li标签 
        document.getElementById('add').onclick = function () {
            let li = document.createElement('li');
            document.getElementById('ul').appendChild(li);
        }
        //给li标签注册鼠标经过事件
        //这样注册的事件通过后面按钮添加的li元素无法改变颜色
        //因为是事件注册的时候还没有该元素
        let liList = document.getElementsByTagName('li');
        for (let i = 0; i < liList.length; i++) {
            liList[i].onmouseover = function (e) {
                e = e || window.event;
                this.className ? this.className = "":this.className = "active"
            }
        }



        //给ul注册委托事件,可以达到给后面添加的li添加事件的效果
        //实现的机制:事件冒泡
        document.getElementById('ul').onmouseover = function (e) {
            e = e || window.event;
            if (e.target.nodeName == 'LI') {
                e.target.className ? e.target.className = "":e.target.className = "active"
            }
        }
    }
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值