简体   繁体   English

使用javascript在循环中注入元素并附加Click事件处理程序

[英]Injecting elements and attaching Click event handlers in a loop with javascript

I'm trying to make a dropdown which is populated from an array with javascript. 我正在尝试制作一个下拉列表,该下拉列表是使用javascript从数组填充的。 Each Item needs to have an event trigger attached, but it currently only attaches the event to the last element. 每个项目都需要附加一个事件触发器,但是当前仅将事件附加到最后一个元素。 I have tried the examples based on fixing closures but is still only attaches to the last element. 我已经尝试过基于固定闭包的示例,但是仍然仅附加到最后一个元素。

https://jsfiddle.net/z3h1uux4/ https://jsfiddle.net/z3h1uux4/

var ArrayUName = ["A","B","C"]
var ArraySlug = ["Q","W","E"]
for (i = 0; i < ArrayUName.length; i++) {
      var GoalID = ArrayUName[i] + '-' + ArraySlug[i];
      document.getElementById("TheContent").innerHTML +=
      '<a class="GoalIDBtn" id="' + GoalID + '">' + ArrayUName[i] + ' / ' + ArraySlug[i] + '</a></br>';
      (function(_i, _GoalID)
          {document.getElementById(_GoalID).addEventListener(
              "click",
               function() {alert("Click Made : " + _i)}
          );
      })(i, GoalID);
      console.log("Loop #" + i);
}

That's because innerHTML is a destructive property. 这是因为innerHTML破坏性的属性。 It recreates the set content and creates new elements, the newly generated elements do no have any click handlers bound to them. 它会重新创建设置内容并创建元素,新生成的元素没有绑定任何click处理程序。 You should create a node (element) instead of using innerHTML . 您应该创建一个节点(元素),而不要使用innerHTML

You can use the document.createElement and HTMLElement.appendChild methods instead: 您可以改用document.createElementHTMLElement.appendChild方法:

var a = document.createElement('a');
a.className = 'GoalIDBtn';
a.id = GoalID;
a.textContent = ArrayUName[i] + ' / ' + ArraySlug[i];
document.getElementById("TheContent").appendChild(a);
(function(_i /*, _GoalID*/) {
  a.addEventListener("click", function() {
      alert("Click Made : " + _i);
  });
})(i);

Here is a demo on jsfiddle . 这是jsfiddle的演示 Note that it doesn't add the br elements and you can use the similar DOM APIs for creating them. 请注意,它不会添加br元素,您可以使用类似的DOM API来创建它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM