2025-01-01 07:00:01

遍历<select>选项

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

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


当前回答

你也可以这样试试。

你的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);
  }

其他回答

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

这对我很有效

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

在尝试了几段代码后,仍然没有工作,我去了select2.js的官方文档。 链接如下: https://select2.org/programmatic-control/add-select-clear-items

因此,清除select select2 js的方法是:

$('#mySelect2').val(null).trigger('change');

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

for (const option of document.getElementById('mySelect')) {
  console.log(option);
}
$("#selectId > option").each(function() {
    alert(this.text + ' ' + this.value);
});

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