如何禁用或隐藏无类名与ID的下拉列表指定选项?
定位并操作指定value的Option元素
一、jQuery实现方案
1. 禁用value=1的选项
通过select的name属性精准定位下拉框,再结合属性选择器匹配value="1"的option,使用prop()设置禁用(布尔属性推荐用prop而非attr):
$('select[name="wpeevent_button_qty_a"] option[value="1"]').prop('disabled', true);
2. 隐藏value=1的选项
部分浏览器对option的display:none支持有限,优先推荐禁用;若需隐藏可使用:
$('select[name="wpeevent_button_qty_a"] option[value="1"]').css('display', 'none');
3. 删除value=1的选项
直接移除该option元素:
$('select[name="wpeevent_button_qty_a"] option[value="1"]').remove();
二、原生JavaScript实现方案
无需依赖jQuery,用原生API也能完成:
1. 禁用选项
const targetOption = document.querySelector('select[name="wpeevent_button_qty_a"] option[value="1"]'); if (targetOption) { targetOption.disabled = true; }
2. 隐藏选项
const targetOption = document.querySelector('select[name="wpeevent_button_qty_a"] option[value="1"]'); if (targetOption) { targetOption.style.display = 'none'; }
3. 删除选项
const targetOption = document.querySelector('select[name="wpeevent_button_qty_a"] option[value="1"]'); if (targetOption) { targetOption.remove(); }
原代码失效原因
你之前的代码$('main-table_5764 select option').attr("disabled","disabled")存在两个问题:
- 选择器缺少前缀:
main-table_5764如果是类名需加.,ID需加#,否则无法定位到父元素; - 未精准匹配目标option:选中了下拉框内所有option,而非仅
value=1的那一个。
内容的提问来源于stack exchange,提问作者Naomi S
相关产品推荐
相关产品推荐

