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

如何在Bootstrap 4中以编程方式修改下拉选择框选项?

如何在Bootstrap 4中编程修改下拉选择框的选项

嘿,我来帮你搞定Bootstrap 4里编程修改下拉选项的事儿~你的下拉框用了Bootstrap的custom-select样式,但本质还是原生的<select>元素,所以直接用原生JS或者jQuery操作就行,下面是几种常见的操作场景:

1. 动态添加新选项

比如想给下拉框加一个"Leather"选项,可以这么做:

原生JavaScript方式:

// 获取目标下拉框元素
const selectElement = document.getElementById('materialType');

// 创建新的option节点
const newOption = document.createElement('option');
newOption.value = 'Leather';
newOption.textContent = 'Leather';

// 将新选项添加到下拉框中
selectElement.appendChild(newOption);

jQuery方式(如果项目里引入了jQuery):

$('#materialType').append('<option value="Leather">Leather</option>');

2. 移除指定选项

比如要移除"Mud"这个选项:

原生JS:

const selectElement = document.getElementById('materialType');
// 定位到目标option并移除
const targetOption = selectElement.querySelector('option[value="Mud"]');
if (targetOption) {
  selectElement.removeChild(targetOption);
}

jQuery:

$('#materialType option[value="Mud"]').remove();

3. 清空所有选项并重新添加

如果需要完全替换下拉的选项列表,可以先清空再批量添加:

原生JS:

const selectElement = document.getElementById('materialType');
// 清空现有所有选项
selectElement.innerHTML = '';

// 准备新的选项数据
const newOptions = [
  { value: 'Material Type', text: 'Material Type' },
  { value: 'All', text: 'All' },
  { value: 'Plastic', text: 'Plastic' },
  { value: 'Metal', text: 'Metal' }
];

// 循环添加新选项
newOptions.forEach(opt => {
  const option = document.createElement('option');
  option.value = opt.value;
  option.textContent = opt.text;
  selectElement.appendChild(option);
});

jQuery:

$('#materialType').empty();
$('#materialType').append(`
  <option value="Material Type">Material Type</option>
  <option value="All">All</option>
  <option value="Plastic">Plastic</option>
  <option value="Metal">Metal</option>
`);

4. 设置默认选中的选项

比如想让"All"成为默认选中项:

原生JS:

document.getElementById('materialType').value = 'All';

jQuery:

$('#materialType').val('All');

小提示:因为你的下拉框用了Bootstrap的custom-select样式,修改选项后不需要额外刷新样式——Bootstrap会自动适配原生<select>的变化,直接操作原生元素就可以啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:24:56