javascript - 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";
});
}
解决方案
我想你正在寻找这个结果?
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>
推荐阅读
- c# - 在 ASP.Net Core 中测试 REST 样式的控制器
- html - 如何在角度 6 中拖放元素?
- android - 为什么在 Firemonkey 中启用 WordWrap 时 TText 修剪不起作用?
- php - 删除 jquery .click 上的特定 SQL 行。(我试图在单击时从数据库中删除图像)
- laravel - 发送变量以终止中间件
- php - 不同的反应
- rxjs - 我如何在一系列可观察数据中记住最后一个结果?
- here-api - 这里 api 没有在 /places/v1/diover/here 中显示特定纬度的任何数据
- selenium-webdriver - 如何使用“XPATH”处理内置关键字的 WebUI.click() 和 WebUI.setText()
- android - Firebase crashlytics 不显示崩溃