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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:23:03  来源:igfitidea点击:

jQuery how to remove :selected attribute and add new one properly

jquery

提问by Somebody

How do I remove :selectedattribute and add new one?

如何删除:selected属性并添加新属性?

采纳答案by Nick Craver

If you're talking about a <select>just set the value using .val()like this:

如果您正在谈论<select>使用.val()如下方式设置值:

$('#mySelect').val('new value');

This automatically selects the <option>with that value.

这会自动选择<option>具有该值的 。

回答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 selectedfrom 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 eachiterates through them, and the removeAttr eliminates the 'selected'.

第一个子句获取所有选定的选项,同时each遍历它们,removeAttr 消除“选定”。