简体   繁体   English

如何禁用下拉元素中的特定项

[英]How to disable particular item in a drop down element

如何使用jQuery或JavaScript禁用下拉元素的某些项?

The same way you would disable any other HTML element, use 与禁用任何其他HTML元素的方式相同,请使用

$(/* option selector */).prop('disabled', true);

See it in action . 看到它在行动

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()javascript根据需要附加属性disabled="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特别是由SOMETHING触发,例如,这可以用来说“当我.click()这个按钮,然后添加.attr()“等

Lots of jQuery, in plain js you get a reference to the option however and just set the disabled property to true. 很多jQuery,在普通的js中你得到了对该选项的引用,只是将disabled属性设置为true。 So given: 所以给出:

<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. 当然,您可以根据您想要的任何标准禁用一个。

$(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>
$("option").attr("disabled", "disabled");

只需使用其他选择器选择所需选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM