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

基于动态Post ID类的jQuery手风琴独立触发问题求助

问题根源

你代码中所有操作.show-more-dts的选择器都是全局匹配,没有限定范围,会选中页面中所有手风琴内容容器,所以点击任意按钮都会触发所有手风琴同步动作。

修复方案

方案1:基于现有动态类逻辑修改(适配你原有写法)

你已经为触发按钮生成了带post ID的专属类,只需要给对应手风琴内容容器也加上带相同post ID的专属类,然后在脚本中限定选择器即可。
首先修改手风琴内容容器的HTML部分,添加专属类:

<div class="show-more-dts show-more-dts-<?php the_ID(); ?>">
<!-- 手风琴内容 -->
</div>

然后修改你的脚本代码:

<script type="text/javascript">
  var postId = "<?php the_ID(); ?>";
  var triggerSelector = ".show-dts." + postId;
  var contentSelector = ".show-more-dts-" + postId;

  $(triggerSelector).click(function() {
    if($(contentSelector).css('height') != '1px'){
      $(contentSelector).stop().animate({height: '1px'}, 200);
      $(this).text('Show details');
    }else{
      $(contentSelector).css({height:'100%'});
      var xx = $(contentSelector).height();
      $(contentSelector).css({height:'1px'});
      $(contentSelector).stop().animate({height: xx}, 400);
      $(this).text('Hide Details');
    }
    return false;
  });
</script>

方案2:通用简化写法(无需每个文章输出独立脚本,性能更优)

你可以把所有逻辑合并成一段全局脚本,通过DOM遍历定位对应内容区,不用依赖动态生成的类,避免循环输出重复脚本。
首先保证每个文章块内包含触发按钮和对应手风琴内容,参考结构:

<div class="post-item">
  <!-- 文章其他内容 -->
  <button class="show-dts">Show details</button>
  <div class="show-more-dts"><!-- 手风琴内容 --></div>
</div>

全局只需要写一次脚本:

<script type="text/javascript">
$('.show-dts').click(function() {
  // 从当前点击的按钮出发,匹配所属文章块下的对应手风琴内容区
  const $content = $(this).closest('.post-item').find('.show-more-dts');
  if($content.css('height') != '1px'){
    $content.stop().animate({height: '1px'}, 200);
    $(this).text('Show details');
  }else{
    $content.css({height:'100%'});
    const contentHeight = $content.height();
    $content.css({height:'1px'});
    $content.stop().animate({height: contentHeight}, 400);
    $(this).text('Hide Details');
  }
  return false;
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:54:03