选择具有层次结构 JSON 的 2 进入选项组?
select2 with hierarchy JSON into option groups?
对于给定的 JSON 结构,如下所示:
{
"fruit": [
{
"id": 1,
"name": "Orange"
},
{
"id": 2,
"name": "Banana"
},
{
"id": 3,
"name": "Apple"
}
],
"vegetables": [
{
"id": 4,
"name": "Potato"
},
{
"id": 5,
"name": "Carrot"
},
{
"id": 6,
"name": "Broccoli"
}
]
}
当将其作为 "data" 传递给 select2 方法时,我如何才能将此信息呈现为像这样的选项组?
<select>
<optgroup label="fruit">
<option>Orange</option>
<option>Apple</option>
<option>Banana</option>
</optgroup>
<optgroup label="vegetable">
<option>Potato</option>
<option>Carrot</option>
<option>Broccoli</option>
</optgroup>
解决方法如下:
<select class="js-example-basic-single"></select>
<script>
var data = {
"fruit": [
{
"id": 1,
"name": "Orange"
},
{
"id": 2,
"name": "Banana"
},
{
"id": 3,
"name": "Apple"
}
],
"vegetables": [
{
"id": 4,
"name": "Potato"
},
{
"id": 5,
"name": "Carrot"
},
{
"id": 6,
"name": "Broccoli"
}
]
};
$().ready(function(){
var parsedJsonString = JSON.stringify(data); // get json string
var parsedJsonObject = $.parseJSON(parsedJsonString); // convert json string to object
$.each(parsedJsonObject,function(ele)
{
$(".js-example-basic-single").append("<optgroup label='" + ele + "'>");
$.each(parsedJsonObject[ele],function(subEle)
{
$(".js-example-basic-single").append("<option value='" + parsedJsonObject[ele][subEle]["id"] + "'>" + parsedJsonObject[ele][subEle]["name"] + "</option>");
});
$(".js-example-basic-single").append("</optgroup>");
});
$(".js-example-basic-single").select2();
});
对于给定的 JSON 结构,如下所示:
{
"fruit": [
{
"id": 1,
"name": "Orange"
},
{
"id": 2,
"name": "Banana"
},
{
"id": 3,
"name": "Apple"
}
],
"vegetables": [
{
"id": 4,
"name": "Potato"
},
{
"id": 5,
"name": "Carrot"
},
{
"id": 6,
"name": "Broccoli"
}
]
}
当将其作为 "data" 传递给 select2 方法时,我如何才能将此信息呈现为像这样的选项组?
<select>
<optgroup label="fruit">
<option>Orange</option>
<option>Apple</option>
<option>Banana</option>
</optgroup>
<optgroup label="vegetable">
<option>Potato</option>
<option>Carrot</option>
<option>Broccoli</option>
</optgroup>
解决方法如下:
<select class="js-example-basic-single"></select>
<script>
var data = {
"fruit": [
{
"id": 1,
"name": "Orange"
},
{
"id": 2,
"name": "Banana"
},
{
"id": 3,
"name": "Apple"
}
],
"vegetables": [
{
"id": 4,
"name": "Potato"
},
{
"id": 5,
"name": "Carrot"
},
{
"id": 6,
"name": "Broccoli"
}
]
};
$().ready(function(){
var parsedJsonString = JSON.stringify(data); // get json string
var parsedJsonObject = $.parseJSON(parsedJsonString); // convert json string to object
$.each(parsedJsonObject,function(ele)
{
$(".js-example-basic-single").append("<optgroup label='" + ele + "'>");
$.each(parsedJsonObject[ele],function(subEle)
{
$(".js-example-basic-single").append("<option value='" + parsedJsonObject[ele][subEle]["id"] + "'>" + parsedJsonObject[ele][subEle]["name"] + "</option>");
});
$(".js-example-basic-single").append("</optgroup>");
});
$(".js-example-basic-single").select2();
});