2025-01-01 07:00:01

遍历<select>选项

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

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


当前回答

这对我很有效

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

其他回答

和必要的,非jquery的方式,为追随者,因为谷歌似乎把每个人都送到这里:

  var select = document.getElementById("select_id");
  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    // now have option.text, option.value
  }

也可以使用带有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);
 });

你也可以这样试试。

你的HTML代码

<select id="mySelectionBox">
    <option value="hello">Foo</option>
    <option value="hello1">Foo1</option>
    <option value="hello2">Foo2</option>
    <option value="hello3">Foo3</option>
</select>

JQuery代码

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

OR

var select =  $('#mySelectionBox')[0];

  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    alert (option.text + ' ' + option.value);
  }

这对我很有效

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

如果你不需要Jquery(可以使用ES6)

for (const option of document.getElementById('mySelect')) {
  console.log(option);
}