通过<select>选项进行迭代

use*_*662 187 jquery

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

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

kar*_*m79 329

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

  • 它应该是$(this).val()而不是像IT ppl所说的this.value. (13认同)
  • @AmitKB - 最好使用原生DOM方法来提取文本和值.1)它更短2)避免构造两个新的jQuery对象. (5认同)
  • 它很奇怪,这应该工作,但由于某种原因它不适合我...... :( (2认同)
  • 应该是 $(this).val() 和 $(this).text() 分别用于获取值和文本 (2认同)

IT *_*ppl 77

这对我有用

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

  • 如果你在一个变量中存储`$(this)`它会更有效,即`var $ this = $(this); $ this.text(); $ this.val(); ... etc.` (5认同)

Aru*_*ngh 24

也可以使用参数化的每个索引和元素.

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

//这也行

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


rog*_*ack 12

对于粉丝而言,这是必不可少的非jquery方式,因为google似乎将所有人都送到了这里:

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


Jey*_*edo 7

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

for (const option of document.getElementById('mySelect')) {
  console.log(option);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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


Dul*_*sta 5

你也可以这样试试。

你的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>
Run Code Online (Sandbox Code Playgroud)

JQuery编码

$("#mySelectionBox option").each(function() {
    alert(this.text + ' ' + this.value);
});
Run Code Online (Sandbox Code Playgroud)

或者

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

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


zza*_*art 5

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

Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))
Run Code Online (Sandbox Code Playgroud)