【发布时间】:2010-06-01 13:30:35
【问题描述】:
我在 HTML 中有一个 <select> 元素。该元素表示一个下拉列表。我试图了解如何通过 JQuery 遍历 <select> 元素中的选项。
如何使用 JQuery 在<select> 元素中显示每个选项的值和文本?我只想在alert() 框中显示它们。
【问题讨论】:
标签: jquery
我在 HTML 中有一个 <select> 元素。该元素表示一个下拉列表。我试图了解如何通过 JQuery 遍历 <select> 元素中的选项。
如何使用 JQuery 在<select> 元素中显示每个选项的值和文本?我只想在alert() 框中显示它们。
【问题讨论】:
标签: jquery
$("#selectId > option").each(function() {
alert(this.text + ' ' + this.value);
});
【讨论】:
这对我有用
$(function() {
$("#select option").each(function(i){
alert($(this).text() + " : " + $(this).val());
});
});
【讨论】:
$(this) 存储在变量中,效率会更高,即var $this = $(this); $this.text(); $this.val();...etc.
$.each($("#MySelect option"), function(){
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
}
【讨论】:
也可以使用带有索引和元素的参数化每个。
$('#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);
});
【讨论】:
如果你不想要 Jquery(并且可以使用 ES6)
for (const option of document.getElementById('mySelect')) {
console.log(option);
}
【讨论】:
在没有 jQuery 的情况下已经提出的答案的另一个变体。
Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))
【讨论】:
你也可以这样试试。
您的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);
});
或
var select = $('#mySelectionBox')[0];
for (var i = 0; i < select.length; i++){
var option = select.options[i];
alert (option.text + ' ' + option.value);
}
【讨论】:
在尝试了几个代码后,仍然无法正常工作,我去了 select2.js 的官方文档。 这里是链接: https://select2.org/programmatic-control/add-select-clear-items
从中清除选择select2 js的方法是:
$('#mySelect2').val(null).trigger('change');
【讨论】: