我需要数组或 JSON 中的选项值列表。 我使用了以下代码。
var compArray=[];
jQuery("#myCombo option").each(function(){
compArray.push(jQuery(this).val());
});
但我不想在循环中迭代选项,因为我的选项列表会增长。 我用过
JSON.stringify(document.getElementById("myCombo").options)
但是在 stringify 上它显示空的 JSON 对象,尽管我可以从
document.getElementById("myCombo").options[0].value
我必须将请求参数中的这些值传递给服务器,我不想经历循环。 请提出优化方案。
最佳答案
您可以像这样使用自定义序列化器:
var options = Array.prototype.slice.call(document.getElementById("sel").options),
str = JSON.stringify(options, function(key, value){
if(key === ""){
return value;
}
if(!isNaN(parseInt(key))) {
return value.value;
}
};
或者使用迭代而不为每个选项创建 jQuery 实例
var options = Array.prototype.slice.call(document.getElementById("sel").options),
str = JSON.stringify(options.map(function(item){return item.value;}));
检查此性能测试:http://jsperf.com/get-options
关于javascript - 在不使用循环或 jQuery 的情况下获取数组或 JSON 中选择的选项值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13450686/