jQuery 禁用基于值的选择选项*仅通过 HTML!*
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7450370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable select options based on value *through the HTML only!*
提问by Ajay
I need to disable a select option based on the value of a variable. The value is similar to one of the select option value and it needs to be disabled.
我需要根据变量的值禁用选择选项。该值类似于选择选项值之一,需要禁用它。
For ex,
例如,
<select>
<option>Value a</option>
<option>Value b</option>
</select>
$variable = <some select option value>;
So if variable is equal to Value a then it needs to be disabled in select option.
因此,如果变量等于 Value a,则需要在选择选项中禁用它。
Thanks.
谢谢。
回答by Joseph Marikle
With your current markup this will work:
使用您当前的标记,这将起作用:
$("select option:contains('Value b')").attr("disabled","disabled");
EDIT
编辑
var variable = "b"
$("select option:contains('Value " + variable + "')").attr("disabled","disabled");
$("select").prop("selectedIndex",-1)
回答by aziz punjani
$("select option[value='"+ $variable + "']").attr('disabled', true);
回答by Philip
This should be a faster solution
这应该是一个更快的解决方案
$('select').children('option[value="' + $variable + '"]').attr('disabled', true)
回答by Marko
Let's say you had the following markup
假设您有以下标记
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Using this jQuery, the saab option would be disabled.
使用此 jQuery,将禁用 saab 选项。
$("select option").each(function() {
var $thisOption = $(this);
var valueToCompare = "saab";
if($thisOption.val() == valueToCompare) {
$thisOption.attr("disabled", "disabled");
}
});