Attach event to dynamic elements in javascript

前端 未结 10 2278
一生所求
一生所求 2020-11-21 23:16

I\'m trying to insert html data dynamically to a list that is dynamically created, but when i try to attach an onclick event for the button that is dynamically created the e

10条回答
  •  梦谈多话
    2020-11-21 23:41

    I know that the topic is too old but I gave myself some minutes to create a very useful code that works fine and very easy using pure JAVASCRIPT. Here is the code with a simple example:

    String.prototype.addEventListener=function(eventHandler, functionToDo){
      let selector=this;
      document.body.addEventListener(eventHandler, function(e){
        e=(e||window.event);
        e.preventDefault();
        const path=e.path;
        path.forEach(function(elem){
          const selectorsArray=document.querySelectorAll(selector);
          selectorsArray.forEach(function(slt){
            if(slt==elem){
              if(typeof functionToDo=="function") functionToDo(el=slt, e=e);
            }
          });
        });
      });
    }
    
    // And here is how we can use it actually !
    
    "input[type='number']".addEventListener("click", function(element, e){
    	console.log( e ); // Console log the value of the current number input
    });
    
    


提交回复
热议问题