简体   繁体   English

为for循环中的每个项目添加一个onclick处理程序

[英]Add an onclick handler for every item in a for-loop

I'm trying to add an onclick event for every button that has a child in my program. 我试图为程序中有孩子的每个按钮添加一个onclick事件。 Initially when I was using getElementsByClassName I was unaware of the fact that it returns an array (obvious now in hindsight) unlike getElementById that only returns one item. 最初,当我使用getElementsByClassName我没有意识到它返回一个数组(事后看来很明显),这一点不同于getElementById仅返回一个项目。 So I edited my code to iterate over all button elements, but still to no avail: 因此,我编辑了代码以遍历所有按钮元素,但仍然无济于事:

window.addEventListener('DOMContentLoaded', run );
function run(){
  allLIElements = document.getElementsByTagName("button")
  for (i=0; i < allLIElements.length; i++){
    var li = allLIElements[i];
    if ( li.firstElementChild != null ){
      li.classList.add('myBtn');
      // tests whether or not the element has been given the proper class
      document.getElementById('check').innerHTML = li.classList;
    }
  };

  }

//**Returns an HTMLcollection not a nodeList**

var btn = document.getElementsByClassName("myBtn");
var span = document.getElementsByClassName("close")[0];
var modal = document.getElementById('myModal');

for (i=0; i < btn.length; i++){
  btn[i].onclick = function() {
    modal.style.display = "block";
};
}
  // When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

EDIT 编辑

Here's a link to show what's happening, so right now when I click on "customer 6" for example I want a modal to appear: https://jsfiddle.net/0k617jsq/ 这是一个显示正在发生的情况的链接,因此,例如,当我单击“客户6”时,现在我希望出现一个模式: https : //jsfiddle.net/0k617jsq/

Basically nothing is happening when I click on the button, the modal isn't activating. 基本上,当我单击该按钮时,什么也没有发生,该模式没有激活。

The docs state that: 文档指出:

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. 当初始HTML文档已完全加载和解析时,无需等待样式表,图像和子帧完成加载,就会触发DOMContentLoaded事件。

This means before the run functions is executed, the javascript engine tries to execute this line: 这意味着在执行run函数之前,javascript引擎会尝试执行以下行:

var btn = document.getElementsByClassName("myBtn");

And since no button probably has the class myBtn at this point, no handlers will be assigned to any button. 而且由于此时没有按钮可能具有myBtn类,因此不会将处理程序分配给任何按钮。 One solution (among many) would be to put the var assignment and the for loop that assigns the onclick events inside the run function. 一种解决方案(其中很多)是将var分配和for循环(用于将onclick事件分配到run函数中)放入。

You should post a working example that shows the issue, otherwise we're left to guess the missing parts. 您应该发布一个显示问题的有效示例,否则我们将猜测丢失的部分。 Below is what can be deduced from your code. 下面是可以从您的代码推论得出的内容。

It more or less works, so if you were to show the HTML, likely a helpful answer will ensue. 它或多或少都起作用,因此,如果要显示HTML,可能会得到有用的答案。 You need to hide the modal on load. 您需要隐藏加载时的模态。

 window.addEventListener('DOMContentLoaded', run ); function run(){ allLIElements = document.getElementsByTagName("button") for (i=0; i < allLIElements.length; i++){ var li = allLIElements[i]; if ( li.firstElementChild != null ){ li.classList.add('myBtn'); // tests whether or not the element has been given the proper class document.getElementById('check').innerHTML = li.classList; } }; } //**Returns an HTMLcollection not a nodeList** var btn = document.getElementsByClassName("myBtn"); var span = document.getElementsByClassName("close")[0]; var modal = document.getElementById('myModal'); // hide modal initially modal.style.display = "none"; for (i=0; i < btn.length; i++){ btn[i].onclick = function() { modal.style.display = ""; // Use empty string, not 'block' }; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } 
 #myModal { border: 1px solid red; } 
 <button class="myBtn">A button <span>with an element child</span></button> <div>Check: <span id="check"></span></div> <div id="myModal">the modal<br> <span class="close">close</span></div> 

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

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