jQuery 将空白选项添加到选择顶部并使其成为 IE 中的选定选项

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

Add blank option to top of select and make it the selected option in IE

jqueryhtmlforms

提问by wkm

HTML:

HTML:

<select id="dropdown">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

jQuery:

jQuery:

$("#dropdown").prepend("<option value='' selected='selected'></option>");

When I run this in FireFox or Chrome, the drop down has the newly inserted blank option selected. When I run it in IE8, it still has Volvo selected. Any ideas?

当我在 FireFox 或 Chrome 中运行它时,下拉列表选择了新插入的空白选项。当我在 IE8 中运行它时,它仍然选择了沃尔沃。有任何想法吗?

http://jsfiddle.net/YFu2h/

http://jsfiddle.net/YFu2h/

回答by Joseph Silber

Change it to this, and it'll work:

将其更改为此,它将起作用:

$("#theSelectId").prepend("<option value=''></option>").val('');

http://jsfiddle.net/YFu2h/1/

http://jsfiddle.net/YFu2h/1/

It seems that IE only evaluates the selectedattribute when it first encounters the select.

似乎 IE 只selected在第一次遇到select.

回答by Mrchief

I'm not sure why your code is not working (maybe it has something to do with the fact that in IE, selectedIndexis readonly) but, doing this works in IE:

我不确定为什么您的代码不起作用(也许这与在 IE 中selectedIndex为只读这一事实有关)但是,在 IE 中执行此操作:

$("#dropdown").prepend("<option value='' selected='selected'></option>");
$("#dropdown")[0].options[0].selected = true;

回答by rickyduck

Try:

尝试:

$("#dropdown").prepend(new Option('', '', true, true));
$("#dropdown option:first").attr("selected", "selected");

Or, if you prefer:

或者,如果您更喜欢:

$("#dropdown").prepend("<option value=''></option>");
$("#dropdown option:first").attr("selected", "selected");

Using the first option is marginally quicker. The blank quotes mean blank value and blank text, so fill them in as you need. You don't need the selected attribute in the prepend now we are adding them afterwards. It's something to do with internet explorer not recognizing it being marked as selected as it has only just been created.

使用第一个选项稍微快一点。空白引号表示空白值和空白文本,因此请根据需要填写。您不需要在 prepend 中选择的属性,现在我们将在之后添加它们。这与 Internet Explorer 没有识别出它被标记为选中有关,因为它刚刚创建。

回答by Dev Chauhan

$("#id").prepend("<option value=' ' selected='selected'></option>");

prepend will add the option to top and selected='selected'will make it selected. As value=' ', so, it is blank value option.

prepend 将选项添加到顶部,selected='selected'将使其被选中。由于 value=' ',所以,它是空值选项。