JavaScript性能优化 - 采用事件委托

464 阅读1分钟

事件委托的本质就是利用事件冒泡的机制,把原本需要绑定在子元素上的响应事件委托给了父元素,使父元素完成事件的监听。这样做的好处是,可以大量减少内存的占用从而减少事件的注册。

<html>
<body>
  <ul id="box">
   <li>1</li>
   <li>2</li>
   <li>3</li>
  </ul>
  <script>
    // 优化前
    const list = document.querySlectorAll('li')
    function showText (ev) {
         console.log(ev.target.innerHTML)
    }
    for (let item of list) {
        item.onClick = showTxt
    }
    // 优化后
    const oUl = document.getElementById('ul');
    oUl.addEventListener('click', showTxt, true);
    function showTxt (ev) {
        const obj = ev.target
        if (obj.nodeName.toLowerCase === 'l1') {
            console.log(obj.innerHTML)
        }
    }
  </script>
</body>
</html>