Javascript 获取下拉最后一个选项的值?

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

Get value of last option of a drop down?

javascripthtml

提问by Mohit Jain

I have dropdown menu..which is dynamic.. How can get value of the last item in that drop down (using jquery is also acceptable)

我有下拉菜单..这是动态的..如何获得该下拉菜单中最后一项的值(使用jquery也是可以接受的)

回答by Pointy

With jQuery it's super easy:

使用 jQuery 非常简单:

var lastValue = $('#idOfSelect option:last-child').val();

With plain Javascript it's not much worse:

使用普通的 Javascript 并没有更糟:

var theSelect = document.getElementById('idOfSelect');
var lastValue = theSelect.options[theSelect.options.length - 1].value;

回答by Felix Kling

With jQuery:

使用 jQuery:

$('select option:last').val()

Of course you should use a proper ID to address the selectelement.

当然,您应该使用正确的 ID 来寻址select元素。

If you mean "menu" it terms of a list, you can do it similar:

如果您的意思是列表中的“菜单”,则可以执行类似的操作:

// gives the text inside the last <li> element
$('#menu li:last').text()

// gives you the attribute 'some_attribute' of the last <li> element
$('#menu li:last').attr('some_attribute')

The key here is to use the :lastselector.

这里的关键是使用:last选择器。

回答by Mr.Hunt

One more way of doing this

这样做的另一种方法

   $('select option').last().val()

or for list

或列表

   $('ul li').last().text()

While above 2 suggestions are perfectly valid, I feel this approach is cleaner than modifying the selector.

虽然以上 2 条建议完全有效,但我觉得这种方法比修改选择器更简洁。

Offcourse you should add id/class of specific select/ul if you want to target the particular menu/list.

如果你想针对特定的菜单/列表,当然你应该添加特定选择/ul 的 id/class。

回答by juanchoelx

Using attributte selected.

使用选择的属性。

$('#SelectName option:last-child').attr('selected', 'selected');

回答by PriyankaK

$('#id_of_select option:last-of-type').click();

$('#id_of_select option:last-of-type').click();

OR

或者

$('#id_of_select option:last-child').click();

$('#id_of_select option:last-child').click();

Both of these should find and click on the last option on any dynamic drop-down list.

这两个都应该找到并单击任何动态下拉列表中的最后一个选项。