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

如何用jQuery实现循环生成的a标签点击动态展开/隐藏对应内容

问题分析与解决方案

你的代码无法正常工作的核心原因是HTML中ID属性必须唯一,但你在循环生成的元素里重复使用了author_bio_wrap_toggle和author_bio_wrap这两个ID,导致jQuery只能识别第一个匹配的元素,点击其他项时无法触发对应的展开/隐藏操作。

修改步骤:

  1. 将循环内的ID替换为类名,避免重复ID冲突
  2. 修改jQuery事件绑定逻辑,通过相对选择器定位当前点击项对应的内容区域

修改后的完整代码:

JavaScript部分:

jQuery(document).ready(function($){
    // 用事件委托绑定类选择器,适配动态生成的元素
    $(document).on('click', '.author_bio_wrap_toggle', function(e){
        e.preventDefault(); // 阻止a标签默认跳转行为
        // 精准定位当前点击项内的目标内容区域
        $(this).find('.author_bio_wrap').slideToggle("slow");
    });
});

PHP循环生成的HTML部分:

<div class="divTable">  
    <div class="bs-example">    
        <div class="list-group">
            <a href="#" class="list-group-item list-group-item-action active">
                <i class="fa fa-home gihombing"></i> List Template Expertisi
            </a>';
            
            while ($rr = $rh->fetchRow()) {  
                $html .= '               
                <a href="#" class="list-group-item list-group-item-action author_bio_wrap_toggle">
                    <div class="d-flex w-100 justify-content-between">
                        <h4>'.$rr['nmpasien'].'</h4>
                        <small>1 hari lalu </small>
                    </div>
                    <p>No MR : '.$rr['ps_mrn'].' , Tindakan : '.$rr['jnisdiit'].'</p>
                    <div class="author_bio_wrap" style="display: none;">
                        <input type="button" class="button111" name="soundOffbutton" value="Isi Hasil" style="width:100px; height:30px; " onclick="silent();" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <input type="button" class="button111" name="soundOffbutton" value="Re-Schedule" style="width:100px; height:30px; " onclick="silent();" >
                    </div>
                </a>';  
            }  

            $html .= '   
        </div>
    </div>
</div>

关键说明:

  • 事件委托机制$(document).on('click', '.class', ...)确保动态生成的元素也能触发点击事件
  • $(this).find('.author_bio_wrap')仅对当前点击项内的内容区域进行操作,不会影响其他列表项
  • 移除了重复的id="soundOffbutton",如果需要单独操作这类按钮,可生成唯一ID(如id="soundOffbutton-'.$rr['ps_mrn'].'")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:40:19