封装一个绑定事件函数,考虑事件代理

/**
  * element: 绑定的元素
  * type: 事件类型
  * select: 事件代理时,被代理的元素tagName
  * fn: 回调
*/
function bindEvent (element, type, select, fn) {
  if (fn == null) {
    fn = select
    select = null
  }
  element.addEventListener(type, e => {
    const target = e.target
    if (select) {
      // 代理
      if (target.matches(select)) {
        fn.call(target, e)
      }
    } else {
      // 普通
      fn.call(target, e)
    }
  })
}

results matching ""

    No results matching ""