将选择选项和optgroup存储在JavaScript数组中 [英] Storing select options and optgroups in a JavaScript array
本文介绍了将选择选项和optgroup存储在JavaScript数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作一个jQuery插件,它通过html循环选择< option>
标签并以不同的格式输出它们。
当循环通过选项,我还想维护它们之间的关系,并且< optgroup>
s。作为一名PHP家伙,我认为多维联合阵列就是答案。所以像这样:
I'm making a jQuery plugin that loops through html select <option>
tags and outputs them in a different format.
When looping through the options, I'd also like to maintain the relationship between them and <optgroup>
s. Being a PHP guy I thought a multidimensional associative array would be the answer. So something like this:
<select>
<optgroup label="group1">
<option>option 1</option>
<option>option 2</option>
</optgroup>
<optgroup label="group2">
<option>option 3</option>
<option>option 4</option>
</optgroup>
</select>
...会变成类似这样的内容:
...would turn into something like this:
myArray = [
['group1'] => ['option 1', 'option 2'],
['group2'] => ['option 3', 'option 4']
];
这可能在 javascript
或 jQuery
?
推荐答案
一些花哨的jQuery代码,我认为它应该工作对其进行了测试,并且按预期工作。
Some fancy jQuery code, I believe it should work tested it, and it works as expected.
var o = {};
$('optgroup').each(function() {
o[this.label] = $(this).find('option').map(function() {
return $(this).text();
}).get();
});
console.log(o);
Live DEMO
这篇关于将选择选项和optgroup存储在JavaScript数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文