我如何通过jQuery传递它的ID来获得一个选择的所有选项?
我只是想获取它们的值,而不是文本。
我如何通过jQuery传递它的ID来获得一个选择的所有选项?
我只是想获取它们的值,而不是文本。
当前回答
我发现它既简短又简单,并且可以在Dev Tool控制台本身进行测试。
$ (" # id选项”)。Each ((index,element)=>console.log(index: ${index},值:${element. log)Value}, text: ${element.text})
其他回答
$('select#id').find('option').each(function() {
alert($(this).val());
});
这将把#myselectbox的选项值放入一个整洁的数组中:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
捷径
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
工作示例
最有效的方法是使用$.map()
例子:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
另一种方法是使用toArray(),以便使用胖箭头函数与map,例如:
const options = $('#myselect option').toArray().map(it => $(it).val())