zoukankan      html  css  js  c++  java
  • 面试整理(3)js事件委托

    事件委托主要用于一个父容器下面有很多功能相仿的子容器,这时候就需要将子容器的事件监听交给父容器来做。父容器之所以能够帮子容器监听其原理是事件冒泡,对于子容器的点击在冒泡时会被父容器捕获到,然后用e.target来判断到底是哪个子容器触发了事件

    示例代码:

    <html>
        <head></head>
        <body>
            <ul id="myul">
                <li>1</li>
                <li>2</li>
                <li>3</li>
                <li>4</li>
            </ul>
        </body>
        <script type="text/javascript">
            var ul = document.getElementById("myul")
            ul.addEventListener('click',function(e){
                alert("选中了:"+e.target.innerHTML)
                console.log(e.target)
            })
        </script>
    </html>

    点击第二个li,console输出<li>2</li>从console的输出我们可以判断出e.target返回的是触发事件的element类型

    然后我们看看这个事件委托会不会冒泡

    <html>
        <head></head>
        <body>
            <div id="mydiv">
                <div>
                234
                    <p>123</p>
                </div>
            </div>
        </body>
        <script type="text/javascript">
            var div = document.getElementById("mydiv")
            div.addEventListener('click',function(e){
                alert("选中了:"+e.target.innerHTML)
                console.log(e.target)
            })
        </script>
    </html>

    点击p,发现只有p的事件触发了,上一级的父组件并没有被输出,所以事件委托中e.target就单指那个被点击的组件

    最后试一下stopPropagation会不会阻止委托的父元素接收事件

    <html>
        <head></head>
        <body>
            <ul id="myul">
                <li>1</li>
                <li>2</li>
                <li>3</li>
                <li>4</li>
            </ul>
        </body>
        <script type="text/javascript">
            var ul = document.getElementById("myul")
            ul.addEventListener('click',function(e){
                alert("选中了:"+e.target.innerHTML)
                console.log(e.target)
            })
            document.getElementsByTagName("li")[0].addEventListener('click',function(e){
                e.stopPropagation()
            })
        </script>
    </html>

    由于阻断了了事件冒泡,所以点击第一个li没有反应。

  • 相关阅读:
    【实验吧】CTF_Web_登录一下好吗?
    各种常用数字格式化
    .Net 4.0 (2)
    springBoot+springSecurity 数据库动态管理用户、角色、权限
    springboot+mybatis+SpringSecurity 实现用户角色数据库管理
    Spring boot中Redis的使用
    spring data jpa的使用
    如何优雅的使用mybatis
    WebJars
    mvn打包的POm文件
  • 原文地址:https://www.cnblogs.com/maskmtj/p/9124841.html
Copyright © 2011-2022 走看看