Javascript 从两个单独的JSon对象JQuery中用OptGroup填充Select

Javascript 从两个单独的JSon对象JQuery中用OptGroup填充Select,javascript,jquery,json,select,optgroup,Javascript,Jquery,Json,Select,Optgroup,我有两个json对象 var type = [{"Id":1,"Name":"This is a name"}]; var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"},]; subType.ParentId引用类型.Id 我希望能够在jQuery中填充select <SELECT> <OPTGROUP LABEL="type.Name" id="type.Id"> <OPTIO

我有两个json对象

var type = [{"Id":1,"Name":"This is a name"}];
var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"},];
subType.ParentId引用类型.Id

我希望能够在jQuery中填充select

<SELECT> 
<OPTGROUP LABEL="type.Name" id="type.Id">        
<OPTION LABEL="subType.Name" value="subType.Id">subType.Name</OPTION>                  
</OPTGROUP>
</SELECT>

子类型.名称

你可以在组合中大声叫喊。访问json的值就是这个问题

在帖子中有一些情况可以解决你的问题

下面的代码只使用“select”作为jquery选择器,因此它将影响页面上的所有SelectBox。 你可能想改变这个

下面的代码也不能处理选择其中一个选项的问题,这可能是您应该注意的

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(''));
var type=[{“Id”:1,“Name”:“这是一个名称”}];
var subType=[{“Id”:2,“ParentId”:1,“Name”:“这是一个名称”}];
var输出=[];
$.each(类型、函数(){
//为每个类型添加一个optgroup
输出推送(“”);
var curId=this.Id;
//用于匹配ParentId的线性搜索子类型数组
$。每个(子类型,函数(k,v){
if(this.ParentId=curId){
output.push(“”+this.Name+“”);
//从子类型数组中删除元素,以便下一次搜索花费更少的时间
亚型:剪接(k,1);
}
});
输出推送(“”);
});
//将此处的“选择”更改为选择框的id
$('select').html(output.join('');

我使用了您的方法,它部分有效,但您能告诉我有什么问题吗?您的子类型的格式已更改。还有一些额外的“[]”