【发布时间】:2022-01-16 07:16:34
【问题描述】:
当我打开一个新的 div 时,我试图关闭另一个 div,但我正在使用循环,所以我使用了 forloop.counter 但它不起作用。当我尝试不使用 forloop.counter 或在循环外使用时,它工作正常,但我想在 for 循环内使用。
page.html
{% for result in results %}
<button class="open-div-button" onclick="openDiv-{{forloop.counter}});">Open Div</button>
<div class="div-content" id="content-{{forloop.counter}}">Content Goes Here</div>
{% endfor %}
<script>
function openDiv(id) {
let model = document.getElementById(`openDiv-${id}`);
model.classList.toggle("active");
}
</script>
<style>
.content {
padding: 10px 20px;
display: none;
background-color: #f1f1f1;
}
.content.active {
padding: 10px 20px;
display: block;
background-color: #f1f1f1;
}
</style>
我也尝试过使用forEach,例如:-
function openDiv(id) {
let model = document.getElementById(`openDiv-${id}`);
document.querySelectorAll(`openDiv-${id}`).forEach(function(div) {
if (div.id == id) {
model.classList.toggle("active");
} else {
model.classList.toggle("active");
}
});
}
但它不工作,也没有显示任何错误。
我想做什么?
当新 div 在 for 循环中打开时,我正在尝试 close 活动 div。
我尝试了很多次,但没有成功。我看到了很多问题,但不幸的是我没有找到forloop.counter 的任何问题。任何帮助将非常感激。提前谢谢你。
【问题讨论】:
-
您的问题是什么?
forloop.count什么都不做,或者你openDiv工作不正常? -
我的问题是,当我打开新的 div 时,打开的 div 没有关闭。
标签: javascript html jquery toggle