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

如何使用JavaScript删除select下拉框中指定的Madrid、Barcelona选项

实现方案

你之前的写法会清空整个select的内容,针对你的需求,分两种场景提供实现:

场景1:按option的value属性删除(仅删除value为Madrid、Barcelona的选项)

const selectMenu = document.getElementById('menu');
// 定义要删除的value列表
const targetValues = ['Madrid', 'Barcelona'];

targetValues.forEach(val => {
  const targetOption = selectMenu.querySelector(`option[value="${val}"]`);
  // 找到对应选项再执行删除,避免报错
  targetOption?.remove();
})

执行后剩余的选项为:

  • value为Select的Select选项
  • value为Sevilla的Barcelona选项

场景2:按option的显示文本删除(删除所有文本为Madrid、Barcelona的选项)

注意你提供的HTML里有一个value为Sevilla、文本为Barcelona的选项,用这个方案会同时删除该选项:

const selectMenu = document.getElementById('menu');
const targetTexts = ['Madrid', 'Barcelona'];

// 倒序遍历避免动态删除导致的索引偏移问题
Array.from(selectMenu.options).reverse().forEach(option => {
  if (targetTexts.includes(option.textContent.trim())) {
    option.remove();
  }
})

执行后剩余的选项仅为value为Select的Select选项。

内容的提问来源于stack exchange,提问作者javi-ur96

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:30:02