zoukankan      html  css  js  c++  java
  • 事件委托

    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript">
            window.onload = function () {
                var aUl = document.getElementById("bubble");
                var aLi = aUl.getElementsByTagName("li");
    
                for(var i = 0; i < aLi.length; i++) {
                    aLi[i].onmouseover = function () {
                        this.style.backgroundColor = "blue";
                    };
                    aLi[i].onmouseout = function () {
                        this.style.backgroundColor = "";
                    }
                    aLi[i].onclick = function () {
                        alert(aLi[i]);
                    }
                }
            };
        </script>
    </head>
    <body>
    <div>
        <ul id = "bubble">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
        </ul>
    </div>
    </body>
    

     通过for循环可以实现事件的绑定,但是又与作用链的存在,又导致了一个经典问题

    这里当你点击li标签的时候,都返回undefined,而不是说对应的0,1,2,3。因为变量无法贮存在内存当中。

    解决这个问题有三种方式:(1)闭包,(2)添加新的属性,(3)事件委托

    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    
    <script type="text/javascript">
        window.onload = function () {
    
            function addEvent(doc, lab, eventarg, func) {
    
                if (window.addEventListener) {
                    doc.addEventListener(eventarg, function (evt) {
                        var ev = evt;
                        var tag = ev.target;
    
                        if (tag.nodeName.toLowerCase() == lab.toLowerCase()) {
                            func(tag);
                        }
    
                    }, false);
                }
                else if (window.attachEvent) {
                    doc.attachEvent('on'+eventarg, function (evt) {
                        var ev = window.event;
                        var tag = ev.srcElement;
    
                        if (tag.nodeName.toLowerCase() == lab.toLowerCase()) {
                            func(tag);
                        } 
                    });
                }
            }
    
            var uls = document.getElementById('bubble'); 
            function test(tag) {
                alert(tag.innerHTML);
            }
            addEvent(uls, 'li', 'click', test);
    
    
        };
    </script>
    </head>
    <body>
    <div>
        <ul id = "bubble">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
        </ul>
    </div>
    </body>

    这里就写了一个事件委托的解决方式。 

  • 相关阅读:
    整数反转
    两数之和
    设计模式-备忘录模式
    设计模式-迭代器模式
    设计模式-中介者模式
    设计模式-观察者模式
    C# OpenFileDialog和SaveFileDialog的常见用法
    SQL数据库表结构的修改(sql2005)
    C# 时间格式处理
    C# 集合类(四)
  • 原文地址:https://www.cnblogs.com/hgonlywj/p/4857240.html
Copyright © 2011-2022 走看看