如何在 IE9 中使用 JQuery 设置选择框的默认值?

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

How to set the default value of a select box using JQuery in IE9?

jqueryselectinternet-explorer-9default-value

提问by User 1034

I have the following select box.

我有以下选择框。

<select id="selId">
     <option id='1' value='1'>1</option>
     <option id='2' value='2'>2</option>
     <option id='3' value='3'>3</option>
     <option id='4' value='4'>4</option>
     <option id='5' value='5'>5</option>
</select>

In jquery I am doing the following to select the value 2 in the select box.:

在 jquery 中,我正在执行以下操作以在选择框中选择值 2。:

...
$("select#selId").find("option#2").attr("selected", "selected");
...

The same code sets the value of 2 in the select box in IE8 and Firefox. But its not working in IE9.

相同的代码在 IE8 和 Firefox 中将选择框中的值设置为 2。但它在 IE9 中不起作用。

I am using JQuery 1.6.1 version

我正在使用 JQuery 1.6.1 版本

回答by DavidGouge

Instead of setting the selectedattribute, just use .val("2").

而不是设置selected属性,只需使用 .val("2")。

See here: jsFiddle

在这里看到:jsFiddle

回答by VAShhh

Anyway, this worked well on IE9if you want to mantain the "SELECTED"attribute

无论如何,如果您想保留该属性,这在IE9上运行良好"SELECTED"

$("select#selId").find("option#2").attr("selected", true);

http://jsfiddle.net/cqENs/

http://jsfiddle.net/cqENs/

回答by andyb

You could use val()to set the option instead - see Change the selected value of a drop-down list with jQuery

您可以使用val()来设置该选项 - 请参阅使用 jQuery 更改下拉列表的选定值

回答by Vivek

change this one

改变这个

$("select#selId").find("option#2").attr("selected", "selected");

into this one

进入这个

$("select#selId").find("option#2").attr("selected", true);