Javascript equivalent to $.on

前端 未结 4 912
时光说笑
时光说笑 2020-12-15 16:24

As somebody who (unfortunately) learned more of jQuery than raw javascript I am just now taking the time to replace all o

4条回答
  •  生来不讨喜
    2020-12-15 17:06

    In modern browsers, you can use Element.closest() to simplify replication of jQuery's .on() method as well as ensure that you capture event bubbling from children of the targeted element (a nuance that some other implementations overlook). Older browsers, including IE, would require a polyfill for this to work.

    const on = (element, event, selector, handler) => {
      element.addEventListener(event, e => {
        if (e.target.closest(selector)) {
          handler(e);
        }
      });
    }
    
    on(document, 'click', '#test', e => {
      console.log('click');
    });

提交回复
热议问题