Implementing jQuery's “live” binder with native Javascript

后端 未结 4 1680
不思量自难忘°
不思量自难忘° 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 01:59

    An alternative to binding an event to dynamically to a specific element could be a global event listener. So, each time you update the DOM with another new element event on that element will also the "catches". An example:

    var mybuttonlist = document.getElementById('mybuttonlist');
    
    mybuttonlist.addEventListener('click', e=>{
      if(e.target.nodeName == 'BUTTON'){
        switch(e.target.name){
          case 'createnewbutton':
            mybuttonlist.innerHTML += '
  • '; break; } } }, false);
    ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }

    In this example I have an event listener on the

      for click events. So, an event happens for all child elements. From the simple event handler I created, you can see that it is easy to add more logic, more buttons (with different or repeating names), anchors etc.

      Going all in, you could add the eventlistener to document instead of the list element, catching all click events on the page and then handle the click events in the event handler.

提交回复
热议问题