You need to enable JavaScript to run this app. 点击view more按钮逐个为同级div添加active类的jQuery实现问题
优惠活动
大模型
产品
解决方案
定价
更多

点击view more按钮逐个为同级div添加active类的jQuery实现问题

完整修改后的jQuery代码

$(document).ready(function(){
  var view_more = '<div class="sibling-div view-more"><a class="view-more-btn">View more</a></div>';
  $(".parent-div .sibling-div:last-child").after(view_more);

  $(".parent-div .view-more-btn").click(function(){
    // 筛选所有内容div,排除按钮容器
    const $contentDivs = $(".parent-div .sibling-div:not(.view-more)");
    // 找到第一个未激活的内容div
    const $target = $contentDivs.filter(":not(.active):first");

    if($target.length) {
      $target.addClass("active");
    } else {
      // 所有内容展示完毕后隐藏按钮,可根据需求保留或删除
      $(this).closest(".view-more").hide();
    }
  });
});

逻辑说明

  • 用:not(.view-more)过滤掉按钮容器,仅选中需要逐个展示的内容项,避免操作错误的元素
  • 每次点击时通过filter(":not(.active):first")匹配第一个未激活的内容div,天然符合按顺序递进的需求
  • 增加边界判断,所有内容全部展示后自动隐藏按钮,避免无效点击
  • 修正了原代码的语法错误:length是jQuery对象的属性,不是方法,不需要加后缀()

原代码问题梳理

  • 直接选择所有.sibling-div加类,会导致全部元素一次性显示
  • 固定写.first-child().next()只会永远选中第二个div,无法实现递进效果
  • 循环逻辑没有按索引判断当前需要激活的元素,还是给所有元素统一加类,无法实现逐个显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 12:18:00