4

我有两个 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>
4

2 回答 2

2

下面的代码仅使用“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(''));
于 2012-03-26T04:03:07.750 回答
0

添加 optgroup 以动态使用 javascript 进行选择

你可以创建 dinamamicaly 组合。访问 json 的值在这个问题中。

如何访问名称中有空格的 Json 对象?

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

于 2012-03-26T02:47:20.147 回答