使用纯JavaScript将事件处理程序附加到动态创建的元素

问题描述 投票:1回答:1

我构建了一个将事件处理程序附加到类的函数。它适用于在页面加载期间已存在于DOM中的元素,但在页面加载后动态添加到DOM的元素上静默失败。我很感激任何建议。下面的代码是我正在开发的名为launchjs https://github.com/bytewarestudios/launchjs的JavaScript库的一部分。已经提出的其他解决方案仅指向我已经知道如何使用的JQuery代码,我需要一个没有JQuery的JavaScript解决方案。

有一种解决方案我认为接近我在Ram swaroop提供的Event binding on dynamically created elements?所需要的但是我不相信它指向我将事件附加到动态创建的元素的根本问题并且它没有解释为彻底作为本页面上接受的答案。

代码的最终结果应该允许用户使用以下代码结构将事件附加到具有类的元素。

l(".className").on("click",function(event){

//do something here

});

JavaScript的:

/*
  The type parameter passed in to this function is "click" and the 
  selector variable value equals .view
  Note: the isClass function returns true if the selector value is prefixed
 with a .
 */

this.on = function(type,fn){//begin on function


    //store the events
    var events = ["click","mouseover","mouseout","submit","dblclick"];


    //if the event array contains the event and the selector is not a class
    if(events.indexOf(type) !== -1 && !isClass()){//begin if then  


   //add the event listenter to the document
   document.addEventListener(type,function(event){//begin function           

           /*
            if the event listener target id equals the selector id passed to the launch
           function and the selectors doesn't contain the . prefix or class prefix.
             */
    if(event.target.id === selector){//begin if then      




              //call the function passed in as a parameter, pass the event so it can be used.
              fn(event);              


           }//end if then

      });//end function    

    }//end if then


    //if the event array contains the event and the selector is a class
    if(events.indexOf(type) !== -1 && isClass()){//begin if then  





            //store the collection of classes
            var classes = document.getElementsByClassName(selector.split(".")[1]);     

        //loop through the classes and add the event listeners
        for(var i = 0; i < classes.length; i++){

            classes[i].addEventListener(type,function(event){//begin addEventListener function        

           //add functionality for classes
           if(event.target.className === selector.split(".")[1] && isClass()){//begin if then  



              //call the function passed in as a parameter,pass the event so it can be used.
              fn(event);

           }//end if then

            });//end addEventListener function

   }//end for loop

        }//end if then         


    };//end on function  
javascript
1个回答
4
投票

您需要在每次添加新元素时运行此代码,同时确保您没有将事件侦听器两次附加到旧元素,或者您可以使用委托事件的技术,例如来自jQuery的.on()

简而言之,您将事件侦听器附加到全局容器,并检查指定类的clicked元素。这是一篇关于这个问题的文章:DOM Event Delegation without jQuery

还有一个图书馆,由同一个人写的特定案例:https://github.com/ftlabs/ftdomdelegate

请参阅我的概念简短示例:

var area = document.getElementsByClassName('clickable-area')[0];

area.onclick = function(e) {
  if (e.target.className === 'add-children') {

    var button = document.createElement('button');
    button.className = 'child-button';
    button.innerText = 'Child button';
    area.appendChild(button);

  } else if (e.target.className === 'child-button') {
    e.target.innerText = 'Dynamically added child is clicked';
  }
}
html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}
.clickable-area {
  display: block;
  cursor: pointer;
  background: #eee;
  width: 100%;
  height: 100%;
}
<div class="clickable-area">
  <button class="add-children">Add children</button>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.