我有一个<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)
IT *_*ppl 77
这对我有用
$(function() {
$("#select option").each(function(i){
alert($(this).text() + " : " + $(this).val());
});
});
Run Code Online (Sandbox Code Playgroud)
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)
如果你不需要 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)
你也可以这样试试。
你的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)
已经提出的答案的另一个变体,没有 jQuery。
Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))
Run Code Online (Sandbox Code Playgroud)