You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django循环中仅首个手风琴可展开,其余失效的问题排查

解决Django循环内手风琴组件失效问题

问题根源

  1. 初始失效:用固定ID(比如#accordion-header)绑定事件时,jQuery只会匹配页面中第一个符合条件的元素,自然只有第一个面板能响应。
  2. 动态ID全失效:大概率是ID生成格式不规范(比如包含空格、特殊字符),或是jQuery选择器没正确对应动态生成的ID,导致事件绑定失败。

最优实现方案(类+相对选择器,无需依赖唯一ID)

1. Django模板代码

{% for subcategory in subcategories %}
  <div class="accordion-item">
    <button class="accordion-header">{{ subcategory.name }}</button>
    <div class="accordion-content">
      <!-- 面板内容示例 -->
      {% for product in subcategory.products.all %}
        <p>{{ product.name }}</p>
      {% endfor %}
    </div>
  </div>
{% endfor %}

2. CSS样式

.accordion-header {
  width: 100%;
  padding: 1rem;
  text-align: left;
  background: #f5f5f5;
  border: none;
  cursor: pointer;
  transition: background 0.2s;
}

.accordion-header:hover {
  background: #eee;
}

.accordion-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
  padding: 0 1rem;
  background: white;
}

.accordion-content.active {
  max-height: 500px; /* 根据实际内容调整高度 */
  padding: 1rem;
}

3. jQuery代码

$(document).ready(function() {
  // 给所有手风琴头部绑定点击事件
  $('.accordion-header').on('click', function() {
    // 定位当前头部对应的内容面板
    const targetContent = $(this).next('.accordion-content');
    // 切换展开/收起状态
    targetContent.toggleClass('active');
    
    // 可选:开启互斥模式(点击一个面板时自动折叠其他面板)
    $('.accordion-content').not(targetContent).removeClass('active');
  });
});

如果坚持用动态ID的修复方案

确保ID格式合法(用subcategory.id生成无特殊字符的唯一ID),同时正确绑定事件:

Django模板

{% for subcategory in subcategories %}
  <button id="accordion-header-{{ subcategory.id }}">{{ subcategory.name }}</button>
  <div id="accordion-content-{{ subcategory.id }}" class="accordion-content">
    <!-- 面板内容 -->
  </div>
{% endfor %}

jQuery代码

$(document).ready(function() {
  {% for subcategory in subcategories %}
    $('#accordion-header-{{ subcategory.id }}').on('click', function() {
      $('#accordion-content-{{ subcategory.id }}').toggleClass('active');
    });
  {% endfor %}
});

注:这种方式会生成大量重复的事件绑定代码,不如类+相对选择器简洁高效,不推荐。

核心注意点

  • HTML中ID必须唯一,循环里绝对不能用固定ID。
  • 用$(this)指代当前点击元素,配合.next()/.siblings()等相对选择器定位面板,完全不需要依赖唯一标识。
  • 用max-height实现平滑过渡,比display: none的生硬切换体验更好。

内容的提问来源于stack exchange,提问作者Pierre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:35:21