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

如何通过jQuery的nextAll方法移除select变更后当前元素后的form-group类div?

修正后的实现方案

嘿,我仔细看了你的代码,发现几个需要调整的地方,这样就能准确实现你想要的效果——当select触发change事件时,移除它之后所有class为form-group的div:

问题分析

  1. andSelf()会误删当前select:你代码里的.andSelf().remove()会把触发事件的select元素也一起删掉,这显然不符合需求,得去掉这个方法。
  2. 选择器不够健壮:div[class=form-group]只能匹配class恰好只有form-group的div,如果div还有其他class(比如form-group mb-3)就匹配不到了,改用.form-group选择器更稳妥。
  3. 变量未声明:this_value、this_name这些变量没有用let/const声明,会变成全局变量,建议加上声明避免潜在问题。

修正后的JS代码

$(document).ready(function() { 
    $("select").on('change', function() { 
        const this_value = this.value; 
        const this_name = $(this).attr('name'); 
        const this_id = $(this).attr('id'); 
        // 移除当前select之后所有class为form-group的元素
        $(this).nextAll(".form-group").remove(); 
    }); 
});

关键说明

  • nextAll(".form-group"):只会选中当前select元素之后所有拥有form-group类的兄弟元素,不会影响当前select本身。
  • 用const声明变量:确保变量不会被意外修改,同时避免全局污染。
  • 保留了你原本获取select属性的代码,如果后续不需要用到这些变量,可以直接删掉,简化代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:07:44