获取下拉列表的最后一个选项的价值?

Moh*_*ain 29 html javascript

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

Poi*_*nty 72

使用jQuery,它非常简单:

var lastValue = $('#idOfSelect option:last-child').val();
Run Code Online (Sandbox Code Playgroud)

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

var theSelect = document.getElementById('idOfSelect');
var lastValue = theSelect.options[theSelect.options.length - 1].value;
Run Code Online (Sandbox Code Playgroud)

  • +1用于引用Javascript"隐藏" (3认同)

Fel*_*ing 9

使用jQuery:

$('select option:last').val()
Run Code Online (Sandbox Code Playgroud)

当然,您应该使用正确的ID来处理select元素.

如果你的意思是"菜单"它是一个列表的术语,你可以这样做:

// 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')
Run Code Online (Sandbox Code Playgroud)

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