我得到像
这样的json数组 [{"Childid":17,"ChildName":"A","Parentid":81,"ParentName":"AA"},
{"Childid":2,"ChildName":"B","Parentid":81,"ParentName":"AA"},
{"Childid":6,"ChildName":"B","Parentid":82,"ParentName":"AB"},
{"Childid":5,"ChildName":"A","Parentid":82,"ParentName":"AB"}]
从此我试图建立一个选择列表。但陷入了optgroup的困境。 首先,我试图从数组中找到所有唯一的父名称。这将作为选择组。
var cnames = [];
$.each(data, function (index, value) {
if ($.inArray(value.ParentName, cnames) == -1) {
cnames.push(value.ParentName);
}
});
然后在两个数组中进行迭代并填充选项[子名称和属性]。
$.each(cnames, function (index, value) {
var begin = index;
data = $.map(data, function (item, a) {
if (value == item.ParentName) {
return begin == index ? "<optgroup label='" + item.ParentName + "'><option value=" + item.Childid + ">" + item.ChildName + "</option>" : "<option value=" + item.Childid + ">" + item.ChildName + "</option>";
}
});
});
但是我的输出就像。
因为在循环之后,开始总是= 0。我只需要在一次调用中避免这些迭代。
更新
做出改变
$.each(cnames, function (index, value) {
var begin = index;
data = $.map(data, function (item, a) {
if (value == item.ParentName) {
begin += 1;
return begin-1 == index ? "<optgroup label='" + item.ParentName + "'><option value=" + item.Childid + ">" + item.ChildName + "</option>" : "<option value=" + item.Childid + ">" + item.ChildName + "</option>";
}
});
});
但是这不会关闭optgroup。
答案 0 :(得分:0)
此解决方案可以帮助您
您可以优化此代码,这是对解决方案的粗略尝试。
<!DOCTYPE html>
<html>
<head>
<title>Optgroup and option HTML snippet by json array</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf8" />
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var data = [
{"Childid":17,"ChildName":"A","Parentid":81,"ParentName":"AA"},
{"Childid":2,"ChildName":"B","Parentid":81,"ParentName":"AA"},
{"Childid":6,"ChildName":"B","Parentid":82,"ParentName":"AB"},
{"Childid":5,"ChildName":"A","Parentid":82,"ParentName":"AB"}
];
/*
We will convert the avobe array something like below:
{
'AA' : [
{"Childid":17,"ChildName":"A","Parentid":81,"ParentName":"AA"},
{"Childid":2,"ChildName":"B","Parentid":81,"ParentName":"AA"}
]
,
'AB' : [
{"Childid":6,"ChildName":"B","Parentid":82,"ParentName":"AB"},
{"Childid":5,"ChildName":"A","Parentid":82,"ParentName":"AB"}
]
}
*/
var groupedData = {};
$.each(data, function(i,d){
if(typeof groupedData[d.ParentName] === 'undefined'){
groupedData[d.ParentName] = [];
}
groupedData[d.ParentName].push(d);
});
/*
Now we will create the final DOM
*/
groupedData = $.map(groupedData, function(gd, i){
var $group = $('<optgroup></optgroup>')
.attr('label',i);
$.each(gd, function(_gdi, _gd){
$group.append(
$('<option></option>')
.html(_gd.ChildName)
.attr('value',_gd.Childid)
);
});
return $group;
});
(function($, undefined){
$(function(){
/*
Rendering the output on document ready
*/
$("#grouped").empty();
$.each(groupedData, function(i,$optGroup){
$("#grouped").append($optGroup);
});
});
})(jQuery);
</script>
</head>
<body>
<select id="grouped">
</select>
</body>
</html>