【问题标题】:Close other div when new div is opened (in forloop.counter)打开新 div 时关闭其他 div(在 forloop.counter 中)
【发布时间】: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


【解决方案1】:

你可以这样做(如果forloop.counter 没有问题):

{% 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 %}
<style>
.div-content{
    padding: 10px 20px;
    display: none;
    background-color: #f1f1f1;
}

.div-content.active {
    padding: 10px 20px;
    display: block;
    background-color: #f1f1f1;
}
</style>
<script>
  function openDiv(id) {
    let model = document.getElementById(`content-${id}`);
    let currentActive = document.querySelector('.div-content.active');
    if(currentActive){
      currentActive.classList.remove('active');
    }

    if(currentActive != model){
      model.classList.add("active");
    }
  }
</script>

【讨论】:

  • 不,没有用。它显示Uncaught TypeError: Cannot read properties of null (reading 'classList')
  • 我编辑了我的答案,你能再试一次吗。
  • 成功了。非常感谢。
  • 但现在的问题是:- 当我打开一个 div 并再次单击以关闭它时,它不会自行关闭。
  • 我又编辑了答案,问题解决了吗?
猜你喜欢
  • 2013-11-24
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多