点击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
相关产品推荐
相关产品推荐

