我正在生成单选按钮取决于jsondata id和名称。但是下面的代码不起作用。如何解决这个问题。
JSON:
{
"a": [
{ "id" : "a1", "family" : "Family" },
{ "id" : "a2", "family" : "Family" },
{ "id" : "a3", "family" : "Family" }
],
"b": [
{ "id" : "b1", "family" : "Family" },
{ "id" : "b2", "family" : "Family" },
{ "id" : "b3", "family" : "Family" }
],
"c": [
{ "id" : "c1", "family" : "Family" },
{ "id" : "c2", "family" : "Family" },
{ "id" : "c3", "family" : "Family" }
]
}
使用Javascript:
generateFamily("a");
function generateFamily(objt) {
var Objct = objt;
$.getJSON("./js/result.json", function(result) {
var testobj = result + "." + Objct;
$.each(testobj, function(i, field) {
var char = "a";
char = "ln-" + char;
$("#dFour").append("<li class=" + char + " style='display: list-item;'><a href='#'><span class='m'><input type='radio' class='fbol_ff' value=" + field.id + " family=" + field.family + "/></span>" + field.family + "</a></li>");
});
});
}
答案 0 :(得分:2)
您需要从JSON数据中读取a
字段。由于您将a
传递给变量objt
。您可以使用Bracket notation
var testobj=result[objt];
而不是
var testobj = result + "." + Objct;
var result = {
"a": [{
"id": "a1",
"family": "Family"
}, {
"id": "a2",
"family": "Family"
}, {
"id": "a3",
"family": "Family"
}],
"b": [{
"id": "b1",
"family": "Family"
}, {
"id": "b2",
"family": "Family"
}, {
"id": "b3",
"family": "Family"
}],
"c": [{
"id": "c1",
"family": "Family"
}, {
"id": "c2",
"family": "Family"
}, {
"id": "c3",
"family": "Family"
}]
};
generateFamily("a");
function generateFamily(objt) {
var testobj = result[objt];
$.each(testobj, function(i, field) {
var char = "a";
char = "ln-" + char;
$("#dFour").append("<li class=" + char + " style='display: list-item;'><a href='#'><span class='m'><input type='radio' class='fbol_ff' value=" + field.id + " family=" + field.family + "/></span>" + field.family + "</a></li>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dFour'></div>
答案 1 :(得分:0)
在循环中使用json的长度。
generateFamily("a");
function generateFamily(objt) {
result = $.getJSON("dta_text.json", function(result) {
$.each(result, function(i, field) {
var char = "a";
char = "ln-" + char;
for (i = 0; i < Object.keys(result).length; i++) {
$("#dFour").append("<li class=" + char + " style='display: list-item;'><a href='#'><span class='m'><input type='radio' class='fbol_ff' value=" + field[i].id + " family=" + field[i].family + "/></span>" + field[i].family + "</a></li>");
}
});
});
}