2025-01-01 07:00:01

遍历<select>选项

我在HTML中有一个<select>元素。该元素表示一个下拉列表。我试图了解如何通过JQuery迭代<select>元素中的选项。

如何使用JQuery在<select>元素中显示每个选项的值和文本?我只是想在一个alert()框中显示它们。


当前回答

另一个没有jQuery的已经提出的答案的变体。

Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))

其他回答

$("#selectId > option").each(function() {
    alert(this.text + ' ' + this.value);
});

http://api.jquery.com/each/ http://jsfiddle.net/Rx3AP/

$.each($("#MySelect option"), function(){
                    alert($(this).text() + " - " + $(this).val());                    
                });

另一个没有jQuery的已经提出的答案的变体。

Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))

这对我很有效

$(function() {
    $("#select option").each(function(i){
        alert($(this).text() + " : " + $(this).val());
    });
});

也可以使用带有index和元素的参数化each。

$('#selectIntegrationConf').find('option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });

//这也可以

$('#selectIntegrationConf option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });