我怎样才能禁用一个 <option>在<选择>基于它在 JavaScript 中的价值? [英] How can I disable an <option> in a <select> based on its value in JavaScript?
问题描述
我有一个 和许多
.每个都有一个独特的价值.我需要使用给定的定义值(不是innerhtml)禁用
.
I have a <select>
with a number of <option>
s. Each has a unique value. I need to disable an <option>
with a given defined value (not innerhtml).
有人知道怎么做吗?
推荐答案
Pure Javascript
使用纯 Javascript,您必须循环浏览每个选项,并单独检查它的值.
Pure Javascript
With pure Javascript, you'd have to cycle through each option, and check the value of it individually.
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
不启用非目标元素:
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
jQuery
使用 jQuery,你可以用一行来完成:
jQuery
With jQuery you can do this with a single line:
$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
不启用非目标元素:
$("option[value='stackoverflow']").attr("disabled", "disabled");
请注意,这个不是不区分大小写的.StackOverflow"将不等于stackoverflow".要获得不区分大小写的匹配,您必须遍历每个匹配项,将值转换为小写,然后进行检查:
Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
不启用非目标元素:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});
这篇关于我怎样才能禁用一个 <option>在<选择>基于它在 JavaScript 中的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!