Implementing jQuery's “live” binder with native Javascript

后端 未结 4 1679
不思量自难忘°
不思量自难忘° 2020-11-29 01:54

I am trying to figure out how to bind an event to dynamically created elements. I need the event to persist on the element even after it is destroyed and regenerated.

<
4条回答
  •  無奈伤痛
    2020-11-29 02:14

    The other solutions are a little overcomplicated...

    document.addEventListener('click', e => {
       if (e.target.closest('.element')) {
           // .element has been clicked
       }
    }
    

    There is a polyfill in case you need to support Internet Explorer or old browsers.

提交回复
热议问题