Javascript 如何禁用下拉元素中的特定项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6840200/
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
How to disable particular item in a drop down element
提问by Royal Pinto
How do you disable some items of a drop down element using jQuery or JavaScript?
如何使用 jQuery 或 JavaScript 禁用下拉元素的某些项目?
回答by Bertrand Marron
回答by alt
Easy!
简单!
<select>
<option value="Opt 1.">Opt 1.</option>
<option class="optionselector" value="Opt 2. I'm disabled!" disabled="disabled">opt 2. I'm disabled!</option>
</select>
Simply append disabled="disabled"
in the tag.
只需附加disabled="disabled"
在标签中。
To do it in jQuery, make sure you've got the latest version loaded, then use the .attr() javascript to append the attribute disabled="disabled"
as needed like so:
要在 jQuery 中执行此操作,请确保您已加载最新版本,然后使用 .attr() javascriptdisabled="disabled"
根据需要附加属性,如下所示:
.click(function(){
$('.optionselector').attr("disabled","disabled");
});
Of course, you'll have to put .click inside of another event or function, so the .click is triggered by SOMETHING in particular, such as, this can be used to say "When I .click() this button, then add .attr()" etc.
当然,您必须将 .click 放在另一个事件或函数中,因此 .click 尤其是由某些东西触发的,例如,这可以用来说“当我 .click() 这个按钮时,然后添加.attr()”等。
回答by RobG
Lots of jQuery, in plain js you get a reference to the option however and just set the disabled property to true. So given:
很多 jQuery,在普通的 js 中,您会获得对该选项的引用,只需将 disabled 属性设置为 true。所以给出:
<form id="aForm" ...>
<select name="aSelect">
<option ...>zero
<option ...>one
<option ...>two
<option ...>three
</select>
...
</form>
then to disable all the options:
然后禁用所有选项:
var options = document.forms['aForm']['aSelect'].options;
for (var i=0, iLen=options.length; i<iLen; i++) {
options[i].disabled = true;
}
Of course you can disable just one based on whatever criterion you want.
当然,您可以根据您想要的任何标准仅禁用一个。
回答by Emil Condrea
$(document).ready(function(){
$('#id').attr('disabled','disabled');
})
and the html
和 html
<form id="fmname" method="get">
<select >
<option id="id">s</option>
</select>
<input type="submit" />
</form>
回答by Igor Dymov
$("option").attr("disabled", "disabled");
Just select needed options with another selector.
只需使用另一个选择器选择所需的选项。