jQuery 如何删除 :selected 属性并正确添加新属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2843675/
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
jQuery how to remove :selected attribute and add new one properly
提问by Somebody
How do I remove :selected
attribute and add new one?
如何删除:selected
属性并添加新属性?
采纳答案by Nick Craver
回答by scunliffe
You want something like
你想要类似的东西
$('#mySelect option:selected').removeAttr('selected');
$('#mySelect option:nth-child(5)').attr('selected','selected');//select the one you want
btw, are you talking about a select list single (e.g. dropdown)?... or a select multiple? - you'll need to adjust accordingly if this is a multi-select.
顺便说一句,您是在谈论单个选择列表(例如下拉列表)吗?...还是选择多个?- 如果这是一个多选,您需要相应地进行调整。
I updated the nth child selector... when setting the selected attribute as square bracket notation [4] doesn't work in the selector.
我更新了第 n 个子选择器......当将 selected 属性设置为方括号表示法 [4] 在选择器中不起作用。
回答by Glenn Gordon
If it is a multi-select and you need to remove the selected
from all rows, you can use the following:
如果是多选并且需要selected
从所有行中删除,则可以使用以下内容:
$("#mySelect option:selected").each(function () {
$(this).removeAttr('selected');
});
The first clause fetches all of the selected options, while the each
iterates through them, and the removeAttr eliminates the 'selected'.
第一个子句获取所有选定的选项,同时each
遍历它们,removeAttr 消除“选定”。