如何通过jQuery的nextAll方法移除select变更后当前元素后的form-group类div?
修正后的实现方案
嘿,我仔细看了你的代码,发现几个需要调整的地方,这样就能准确实现你想要的效果——当select触发change事件时,移除它之后所有class为form-group的div:
问题分析
andSelf()会误删当前select:你代码里的.andSelf().remove()会把触发事件的select元素也一起删掉,这显然不符合需求,得去掉这个方法。- 选择器不够健壮:
div[class=form-group]只能匹配class恰好只有form-group的div,如果div还有其他class(比如form-group mb-3)就匹配不到了,改用.form-group选择器更稳妥。 - 变量未声明:
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
相关产品推荐
相关产品推荐

