<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>高阶函数 - 惰性加载函数</title>
</head>
<body>
    <div style="width: 100px; height: 100px; background: #f60;" id="div1"></div>
    <script>
        /**
         * 根据作用域链内部会重写外部的addEvent变量(如果在1. 2.处, 在addEvent前加上var就不是惰性了)
         */
        var addEvent = function(ele, type, handler) {
            if (window.addEventListener) {    // 标准
                addEvent = function(ele, type, handler) {    // 1.
                    ele.addEventListener(type, handler, false);
                };
            } else if (window.attachEvent) {
                addEvent = function(ele, type, handler) {    // 2.
                    ele.attachEvent('on' + type, handler);
                };
            };
            addEvent(ele, type, handler);
        };

        var div = document.querySelector('#div1');
        addEvent(div, 'click', function() {
            console.log(111);
        });

        addEvent(div, 'click', function() {
            console.log(222);
        })

    </script>
</body>
</html>

 

相关文章:

  • 2018-12-01
  • 2022-12-23
  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2021-10-09
  • 2020-03-11
猜你喜欢
  • 2021-07-29
  • 2022-12-23
  • 2021-08-08
  • 2021-12-15
  • 2022-01-19
  • 2022-12-23
相关资源
相似解决方案