Javascript jQuery $.removeAttr("selected") 改变选中的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8226702/
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-24 05:11:54  来源:igfitidea点击:

jQuery $.removeAttr("selected") changes selected option

javascriptjquery

提问by Maxim

Please take a look at the example: http://jsfiddle.net/HHDpK/1/

请看一下例子:http: //jsfiddle.net/HHDpK/1/

As you see the difference between two choosers is only the line

如您所见,两个选择器之间的区别仅在于行

$("#chooser-1 .y").removeAttr("selected");

But as a result their states are different (especially in Chrome). Am I missing anything, or it is a bug?

但结果它们的状态是不同的(尤其是在 Chrome 中)。我错过了什么,还是一个错误?

采纳答案by Shadow Wizard is Ear For You

Looks like internal bug of jQuery with attributes.

看起来像带有属性的 jQuery 的内部错误。

Note that in older versions, before .prop()was introduced in 1.6 version, it works as expected.

请注意,在旧版本中,.prop()在 1.6 版本中引入之前,它按预期工作

In the newer versions, just use .prop()to deal with such properties of elements:

在较新的版本中,仅用于.prop()处理元素的此类属性:

$("#chooser-1 .x").prop("selected", "selected");
$("#chooser-1 .y").removeProp("selected");

jsFiddle update.

jsFiddle 更新

More than that - using .removeProp("selected")on the element selected previously with prop()will cause the original selection to return instead of having nothing selected - ideal behavior.

更重要的是 -.removeProp("selected")在先前选择的元素上使用 withprop()将导致原始选择返回而不是没有选择任何东西 - 理想的行为。

回答by asked_io

I found the above answer failed as well, I had to set the prop to false to get the selected items to not be.

我发现上面的答案也失败了,我必须将道具设置为 false 才能使所选项目不存在。

$("#chooser-1 .x").prop("selected", false);

removeProp cause undesired effects such as not being able to re-select the options again.

removeProp 会导致不良影响,例如无法再次重新选择选项。

I use jquery 1.6.2

我使用 jquery 1.6.2