我有两个 json 对象
var type = [{"Id":1,"Name":"This is a name"}];
var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"},];
subType.ParentId 引用type.Id
我希望能够在 jQuery 中填充一个选择
<SELECT>
<OPTGROUP LABEL="type.Name" id="type.Id">
<OPTION LABEL="subType.Name" value="subType.Id">subType.Name</OPTION>
</OPTGROUP>
</SELECT>
最佳答案
下面的代码仅使用“select”作为 jquery 选择器,因此它将影响页面上的所有选择框。 您可能想要更改此设置。
下面的代码也没有处理选择其中一个选项,这可能是您应该注意的事情。
var type = [{"Id":1,"Name":"This is a name"}];
var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"}];
var output = [];
$.each(type, function(){
//for each type add an optgroup
output.push('<optgroup label="'+this.Name+'">');
var curId = this.Id;
//linear search subTypes array for matching ParentId
$.each(subType, function(k,v){
if( this.ParentId = curId ){
output.push('<option label="'+this.Name +'" value="'+ this.Id +'">'+ this.Name +'</option>');
//DELETE the element from subType array so the next search takes less time
subType.splice(k,1);
}
});
output.push('</optgroup>');
});
//change the 'select' here to the id of your selectbox
$('select').html(output.join(''));
关于javascript - 从两个单独的 JSON 对象 JQuery 使用 OptGroup 填充选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9865922/