Native JS equivalent to jQuery delegation

后端 未结 5 1192
予麋鹿
予麋鹿 2020-12-03 08:02

What is the native implementation for event delegation on dynamically created dom elements?

I tried looking at the jQuery source but I can\'t follow the .on

5条回答
  •  离开以前
    2020-12-03 08:53

    Felt like doing some code golfing ;)

    108 bytes (based on @Bergi)

    (e,d,g,h,b)=>e.addEventListener(d,c=>{for(d=e,b=c.target;b!=d;)b.matches(g)?h.call(d=b,c,b):b=b.parentNode})
    

    Working demo:

    window.$on = (e,d,g,h,b)=>e.addEventListener(d,c=>{for(d=e,b=c.target;b!=d;)b.matches(g)?h.call(d=b,c,b):b=b.parentNode})
    
    $on(document.body, 'click', '.clickable', (evt, matched) => {
      console.log(matched)
    })
    not clickable
    clickable
    clickable
    child element

提交回复
热议问题