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

Blazor动态数据源页面折叠卡片实现方案求助

Fixing Dynamic Bootstrap Collapse Cards & Homepage Redirect Issue

Dynamic Data Compatibility Fix

Ditching individual bool variables for each collapse is the way to go—use a single state to track which collapse is open. This works for any dynamic dataset:

  1. Track the active collapse ID (example using React; adapt to your framework):

    const [activeCollapse, setActiveCollapse] = useState(null);
    
  2. Toggle function for dynamic items:

    const toggleCollapse = (faqId) => {
      setActiveCollapse(activeCollapse === faqId ? null : faqId);
    };
    
  3. Render dynamic FAQ cards:

    {yourDynamicFAQData.map(faq => (
      <div class="card" key={faq.id}>
        <div class="card-header" onClick={() => toggleCollapse(faq.id)}>
          <button class="btn btn-link">{faq.question}</button>
        </div>
        <div class={`collapse ${activeCollapse === faq.id ? 'show' : ''}`} id={`faq-collapse-${faq.id}`}>
          <div class="card-body">{faq.answer}</div>
        </div>
      </div>
    ))}
    

Stop the href="#" Redirect

If you’re using Bootstrap’s native data-toggle, href="#" is causing the page jump because it’s a default anchor behavior. Fix it with one of these:

  • Use the correct target ID in href:

    <a class="btn btn-link" data-toggle="collapse" href="#faq-collapse-1" aria-expanded="false" aria-controls="faq-collapse-1">
      Your Question Here
    </a>
    
  • Swap href for data-target (better for buttons):

    <button class="btn btn-link" data-toggle="collapse" data-target="#faq-collapse-1" aria-expanded="false" aria-controls="faq-collapse-1">
      Your Question Here
    </button>
    
  • Prevent default if you must use #:

    document.querySelectorAll('[data-toggle="collapse"][href="#"]').forEach(el => {
      el.addEventListener('click', e => e.preventDefault());
    });
    

Pro tips:

  • Always generate unique IDs for dynamic collapses (like faq-collapse-${faq.id}) to avoid conflicts.
  • The single state approach scales infinitely—no need to add new variables every time you add a FAQ item.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:32:49