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

使用bootstrap-select多选时如何获取选中选项ID并实现下拉级联过滤

解决Bootstrap-Select多级下拉框联动过滤问题

核心思路是直接操作原生<option>元素(这是bootstrap-select的数据源),再通过组件的refresh方法同步更新UI,而非修改组件生成的外层DOM。以下是具体实现方案:

1. 完整HTML结构示例

假设你有三级下拉框(父→子→孙),按规则给选项添加ID和对应类名:

<select id="parent" class="selectpicker">
  <option id="parent_id_1">父选项1</option>
  <option id="parent_id_2">父选项2</option>
  <option id="parent_id_3">父选项3</option>
</select>

<select id="child_1" class="selectpicker">
  <option id="child_id_1" class="parent_id_1">子选项1-1(归属父1)</option>
  <option id="child_id_2" class="parent_id_1">子选项1-2(归属父1)</option>
  <option id="child_id_3" class="parent_id_2">子选项1-3(归属父2)</option>
  <option id="child_id_4" class="parent_id_2">子选项1-4(归属父2)</option>
  <option id="child_id_5" class="parent_id_3">子选项1-5(归属父3)</option>
</select>

<select id="child_2" class="selectpicker">
  <option id="grandchild_id_1" class="child_id_1">孙选项1-1-1(归属子1-1)</option>
  <option id="grandchild_id_2" class="child_id_1">孙选项1-1-2(归属子1-1)</option>
  <option id="grandchild_id_3" class="child_id_3">孙选项1-3-1(归属子1-3)</option>
</select>

2. jQuery实现联动过滤

// 父下拉框选中事件
$('#parent').on('changed.bs.select', function() {
  // 获取当前选中父选项的ID
  const selectedParentId = $(this).find('option:selected').attr('id');
  
  // 遍历子下拉框的所有原生option,显示匹配类名的选项,隐藏其他
  $('#child_1').find('option').each(function() {
    const $option = $(this);
    $option.toggle($option.hasClass(selectedParentId));
  });
  
  // 刷新子下拉框UI,同步变化
  $('#child_1').selectpicker('refresh');
  
  // 重置孙下拉框(可选:父选项切换后清空孙选项选中状态并隐藏所有)
  $('#child_2').selectpicker('val', '');
  $('#child_2').find('option').hide();
  $('#child_2').selectpicker('refresh');
});

// 子下拉框选中事件,过滤孙下拉框
$('#child_1').on('changed.bs.select', function() {
  const selectedChildId = $(this).find('option:selected').attr('id');
  
  $('#child_2').find('option').each(function() {
    const $option = $(this);
    $option.toggle($option.hasClass(selectedChildId));
  });
  
  $('#child_2').selectpicker('refresh');
});

// 页面初始化:隐藏所有子级选项(可选)
$(document).ready(function() {
  $('#child_1, #child_2').find('option').hide();
  $('#child_1, #child_2').selectpicker('refresh');
});

关键注意点

  • 必须使用bootstrap-select提供的changed.bs.select事件,而非原生change事件,确保组件UI更新后能正确触发逻辑。
  • 始终操作原生<option>,不要直接修改组件生成的.dropdown-menu列表项——原生option是组件的数据源,修改后调用selectpicker('refresh')就能自动同步UI。
  • 如果需要“禁用选项”而非“隐藏”,可以把toggle()换成prop('disabled', !$option.hasClass(xxx)),同样调用refresh生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:25:18