我想使用 jquery 和 json 数据生成 html,但它是嵌套的。
所以我有 json 数据:
{
"A" : ['a1','b1','c1'],
"B" : ['a2','b2','c2'],
"C" : ['a3','b3','c3']
}
我想像这样附加到我的html中:
<select option="A">
<optgroup label ="A">
<option>a1</option>
<option>b1</option>
<option>c1</option>
</optgroup>
<optgroup label ="B">
<option>a2</option>
<option>b2</option>
<option>c2</option>
</optgroup>
</select>
我可以使用 jquery.each 来实现这个吗?这对我的网络性能有好处吗?或者有什么更好的方法可以使用?
额外的问题是,数据溢出,但我可以过滤它,因为我只需要数组的一部分,而不是全部。
var shownData = ['A', 'C']
:这意味着我只想显示 2 个 optgroup,A 和 C
我尝试过使用嵌套jquery,但它未定义,可能是因为它是字符串(?),如下所示:
var arr = ['A'];
$.JSON("JSON.json", function(data){
$.each(arr, function(index, value){
$.each(data.value,function(i,val){
console.log(val);
});
});
})
哦..使用它作为数组..解决它:D
var arr = ['A'];
$.JSON("JSON.json", function(data){
$.each(arr, function(index, value){
$.each(data[value],function(i,val){
console.log(val);
});
});
})
那还有什么更好的方法吗?...
最佳答案
$.each()
基本上是一个带有回调的 for (name in object)
,但据我所知 forEach
通常更快比 for 循环。以下可能是第二快的方法:
var optGroup,
option,
select = document.getElementById('select');
for (og in obj) {
optGroup = document.createElement('optgroup');
optGroup.setAttribute('label', og);
select.appendChild(optGroup);
obj[og].forEach(function(opt) {
option = document.createElement('option');
option.textContent = opt;
optGroup.appendChild(option);
})
}
演示 -> http://jsfiddle.net/d7zys0z1/
最快的方法是在 documentFragment 中构建它之后注入(inject) DOM。
关于javascript - 嵌套jquery有大量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33497225/