封装绑定事件的处理函数(事件代理)

    <ul id="list">
      <li id="li1">项目一</li>
      <li>项目二</li>
      <li>项目三</li>
      <li>项目四</li>
    </ul>
      const list = document.getElementById('list')
      const li1 = document.getElementById('li1')
      function addEvent(ele, type, selector, cb) {
        if (!cb) {
          cb = selector
          selector = null
        }
        ele.addEventListener(type, (e) => {
          // e.stopPropagation()
          if (selector) {
            const target = e.target
            if (target.matches(selector)) cb(e)
          } else {
            cb(e)
          }
        })
      }
      addEvent(li1, 'click', (e) => {
        console.log(e.target.innerHTML)
      })
      addEvent(list, 'click', 'li', (e) => {
        console.log(e.target.innerHTML)
      })

 

上一篇:Vue前端路由及异步组件


下一篇:PHP 日期格式中 Y与y