javascript 如何使用 JQuery 从 JSON 对象创建此选择列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11921226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create this select list from a JSON object using JQuery?
提问by Kiada
Yeah, I have 3 or 4 different answers on the same subject but I'm struggling to combine them to create what I need. I serialize my results using Json.Net which results in the following object:
是的,我对同一主题有 3 或 4 个不同的答案,但我正在努力将它们结合起来以创建我需要的答案。我使用 Json.Net 序列化我的结果,这会产生以下对象:
"[ { "Id": 1, "OrderInList": 1 },
{ "Id": 2, "OrderInList": 2 },
{ "Id": 4, "OrderInList": 3 }
]"
I'd like the option value andtext to be the OrderInList value (I'll use the Id with something else later).
我希望选项值和文本是 OrderInList 值(稍后我会将 Id 与其他内容一起使用)。
I've currently got the following code, but it creates 143option boxes. I can see why it's doing it, but I'm not sure how to alter it to get it to work.
我目前有以下代码,但它创建了143 个选项框。我可以理解它为什么这样做,但我不确定如何更改它以使其正常工作。
$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, null, function (jsonResult) {
$('#orderInList').attr('enabled', 'true');
$.each(jsonResult, function() {
$.each(this, function(index, item) {
$('#orderInList').append(
$("<option></option>")
.text(index)
.val(index)
);
});
});
Any help would be appreciated!
任何帮助,将不胜感激!
回答by thecodeparadox
I think you're trying something like this:
我想你正在尝试这样的事情:
var jsonResult = [{
"Id": 1,
"OrderInList": 1},
{
"Id": 2,
"OrderInList": 2},
{
"Id": 4,
"OrderInList": 3}
]
$('#orderInList').attr('enabled', 'true');
$.each(jsonResult, function() {
$('#orderInList').append(
$("<option></option>").text(this.Id).val(this.OrderInList);
);
});?
Full code
完整代码
$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, function(jsonResult) {
$('#orderInList').attr('enabled', 'true');
$.each(jsonResult, function() {
$('#orderInList').append(
$("<option></option>").text(this.Id).val(this.OrderInList)
);
});
});?
回答by Kevin Bowersox
You do not need the extra call to .each that is nested within the first call to .each. Just pass the items and the index in the first .each call then create your element. Try this:
您不需要对 .each 的额外调用,该调用嵌套在对 .each 的第一次调用中。只需在第一个 .each 调用中传递项目和索引,然后创建您的元素。试试这个:
var json = [ { "Id": 1, "OrderInList": 1 },
{ "Id": 2, "OrderInList": 2 },
{ "Id": 4, "OrderInList": 3 }
];
function createSelect(options){
$.each(options,function(index,item){
$("#orderInList").append($("<option></option>").attr("value", item.OrderInList).text(item.OrderInList));
});
}
$(document).ready(function(){
createSelect(json);
});
Working Example: http://jsfiddle.net/BzC9N/
工作示例:http: //jsfiddle.net/BzC9N/