jQuery 组合框默认选择最后一个选项

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

Combo Box by default selected the last option

jqueryhtml

提问by Bunlong

I want a combobox by default selected the last option (using jquery):

我希望组合框默认选择最后一个选项(使用 jquery):

<select>
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option>item5</option>
</select>

回答by

Do something like this:

做这样的事情:

$(function() {
    $("select option:last").attr("selected", "selected");
});

回答by Oriol

A plain JavaScript solution:

一个普通的 JavaScript 解决方案:

select.selectedIndex = select.options.length-1;

Demo

演示

回答by U.P

<select>
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option selected="selected">item5</option>
</select>

回答by Francis Musignac

Use "prop" instead of "attr", of course depending of what version of jQuery you are using.

使用“prop”而不是“attr”,当然这取决于您使用的 jQuery 版本。

$("select option:last").prop("selected", "selected");

$("select option:last").prop("selected", "selected");

jQuery prop: http://api.jquery.com/prop/

jQuery 道具:http: //api.jquery.com/prop/

More discussion on the subject of when to use prop or attr: .prop() vs .attr()

关于何时使用 prop 或 attr 的更多讨论: .prop() vs .attr()

回答by Juanma Menendez

Just using vanilla Javascript you can combine .selectedIndexand .lengthproperties of the < select >dom object in order to achieve this:

只需使用 vanilla Javascript,您就可以组合< select >dom 对象的.selectedIndex.length属性以实现此目的:

document.querySelector("#mySelect").selectedIndex = document.querySelector("#mySelect").length - 1;
<select id="mySelect">
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option>item5</option>
</select>