首页 > 解决方案 > js中for循环中的addEventListener

问题描述

我正在尝试在答案块上创建一个 for循环,并且我想让答案的高度为 30px 我尝试将事件添加到块中,但它对我不起作用,那为什么呢?

这是我的解决方案:

HTML 代码:

<div class="blocks block-1">
    <div class="questionContainer">
        <div class="questions">How many team members can I invite?</div>
        <div class="answers">
            You can invite up to 2 additional users on the Free plan. There is
            no limit on team members for the Premium plan.
        </div>
    </div>
</div>
<div class="blocks block-2">
    <div class="questionContainer">
        <div class="questions">What is the maximum file upload size?</div>
        <div class="answers">
            No more than 2GB. All files in your account must fit your allotted
            storage space.
        </div>
    </div>
</div>

JavaScript 代码:

const block = document.getElementsByClassName(".blocks");
const answers = document.getElementsByClassName(".answers");

for (i = 0; i < block.length; i++) {
    block[i].addEventListener("click", () => {
        answers[i].style.height = "30px";
    });
}

标签: javascriptfor-loopdomdom-events

解决方案


我想你正在寻找这个结果?

const All_blocks = document.querySelectorAll('.blocks');

All_blocks.forEach( blk =>
  {
  blk.addEventListener('click', () =>
    {
    blk.classList.toggle('show_answer')
    })
  })
.blocks {
  margin  : .5em;
  padding : .3em;
  }
.questions {
  color  : darkblue;
  cursor : pointer;
  }
.blocks .answers  {
  visibility: hidden;
  }
.blocks.show_answer .answers {
  visibility: visible;
  }
<div class="blocks block-1">
  <div class="questionContainer">
    <div class="questions">How many team members can I invite?</div>
    <div class="answers">
      You can invite up to 2 additional users on the Free plan. 
      There is no limit on team members for the Premium plan.
    </div>
  </div>
</div>
<div class="blocks block-2">
  <div class="questionContainer">
    <div class="questions">What is the maximum file upload size?</div>
    <div class="answers">
      No more than 2GB. All files in your account must fit your 
      allotted storage space.
    </div>
  </div>
</div>


推荐阅读