简体   繁体   English

JS-单击按钮会将元素的文本更改为未定义

[英]JS - Clicking buttons changes text of element to undefined

Clicking the buttons 'hi' and 'helo' must change the content of '.admin-text' to the respective text according to the plan, but it simply changes it to 'undefined' . 单击按钮“ hi”和“ helo”必须根据计划将'.admin-text'的内容更改为相应的文本,但是只需将其更改为'undefined'

 var admin_text = document.querySelector('.admin-text'); var infra_btns = [document.getElementById('hi'), document.getElementById('helo')]; var infra_html = ["<p>hi</p>", "<p>helo</p>"]; for(var i = 0; i < 2; i++) { infra_btns[i].addEventListener('click', function() { admin_text.innerHTML = infra_html[i]; }); } 
 <div class="admin"> <div class="admin-nav"> <button class="adminbtns" id="hi">hi</button> <button class="adminbtns" id="helo">helo</button> </div> <div class="admin-text"> </div> </div> 

You're almost there - you need to use let instead of var in your for -loop, otherwise i equals 2 in all your listener functions: 您快到了-您需要在for -loop中使用let而不是var ,否则在所有侦听器函数中i等于2:

 var admin_text = document.querySelector('.admin-text'); var infra_btns = [hi, helo]; var infra_html = ["<p>hi</p>", "<p>helo</p>"]; for (let i = 0; i < 2; i++) { infra_btns[i].addEventListener('click', function() { admin_text.innerHTML = infra_html[i]; }); } 
 <div class="admin"> <div class="admin-nav"> <button class="adminbtns" id="hi">hi</button> <button class="adminbtns" id="helo">helo</button> </div> <div class="admin-text"></div> </div> 

This happens because variables declared using var have function scope , and i in your listener functions is passed by reference , not by value , so all your listeners share the same i . 发生这种情况是因为使用var声明的变量具有函数作用域 ,并且侦听器函数中的i是通过引用而不是通过传递的,因此所有侦听器都共享相同的i After the last iteration the last thing the for -loop does is i++ , so i equals 2. So your listener tries to access infra_html[2] which is undefined because your array does not have an element with that index. 在最后一次迭代之后, for -loop要做的最后一件事是i++ ,所以i等于2。因此,您的侦听器尝试访问undefined infra_html[2] ,因为您的数组没有带有该索引的元素。

This post explains it in detail: JQuery not appending correct value to unordered list 这篇文章对此进行了详细说明: JQuery没有将正确的值附加到无序列表

The problem is in the loop you have 问题出在你的循环中

for(var i = 0; i < 2; i++)
{
  infra_btns[i].addEventListener('click', function() {
    admin_text.innerHTML = infra_html[i];
  });
}

When the client event handler triggers i will be 3, as the loop has ended previously. 当客户端事件处理程序触发时,我将为3,因为循环之前已结束。 You should create a closure. 您应该创建一个关闭。

for(var i = 0; i < 2; i++)
{
   infra_btns[i].addEventListener('click', (function(index) {
      return function () {
         admin_text.innerHTML = infra_html[index];
      }
   })(i));
}

or use let to create block scoped variable as shown in other answer 或使用let创建块作用域变量,如其他答案所示

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

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