我从JSON文件中获取了一些数据,我是这样做的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JSON Sample</title>
</head>
<body>
<div id="placeholder"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://1xxxxxx:xx/vvccvyC_19-90.json',
function(data) {
var output="<ul>";
for (var i in data.lbclassic) {
if (data.lbclassic[i].ageinweeks==19) {
alert('ok');
}
output+="<li id="/data.lbclassic[i]
.ageinweeks/">" + data.lbclassic[i].ageinweeks + "--" +
data.lbclassic[i].cumul + "--" +
data.lbclassic[i].perhh+ "--" +
data.lbclassic[i].perhd+ "--" +
data.lbclassic[i].eggweightinweek+ "--"
+ data.lbclassic[i].eggmasscumul1+ "--"
+ data.lbclassic[i].
eggmassinweek+ "--" + data.lbclassic[i].eggmasscumul
+"</li>";
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
</body>
</html>
稍后我想显示或隐藏列表中的一些元素,为此我需要他们的ID。如何将ID添加到每个<li>
元素?我希望这个ID是我带来的 data.lbclassic [i] .ageinweeks 数据。
举个例子。这是我从JSON带来的第一行:<li>19--0.7--10--10--45--45--4.5--0.03</li>
,我希望它是<li id=19>19--0.7--10--10--45--45--4.5--0.03
;我尝试了各种解决方案但没有工作,我要么得到NaN错误,要么只是我添加的文本而不是数字本身。我读了堆栈周围的各种线程,但没有一个来自JSON。
编辑:这是JSON
{
"lbclassic": [
{
"ageinweeks": 19,
"cumul": 0.7,
"perhh": 10,
"perhd": 10,
"eggweightinweek": 45,
"eggmasscumul1": 45,
"eggmassinweek": 4.5,
"eggmasscumul": 0.03
},
{
答案 0 :(得分:1)
你需要稍微改变一下
$.getJSON('http://1xxxxxx:xx/vvccvyC_19-90.json',
function(data) {
var output="<ul>";
for (var i in data.lbclassic) {
if (data.lbclassic[i].ageinweeks==19) {
alert('ok');
}
output+="<li id='"+data.lbclassic[i].ageinweeks+"'>" +
+data.lbclassic[i].ageinweeks + "--" +
data.lbclassic[i].cumul + "--" +
data.lbclassic[i].perhh+ "--" +
data.lbclassic[i].perhd+ "--" +
data.lbclassic[i].eggweightinweek+ "--"
+ data.lbclassic[i].eggmasscumul1+ "--"
+ data.lbclassic[i].
eggmassinweek+ "--" + data.lbclassic[i].eggmasscumul
+"</li>";
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
连接data.lbclassic[i].ageinweeks
的方式是错误的。
答案 1 :(得分:1)
您需要替换
output+="<li id="/data.lbclassic[i]
.ageinweeks/">"
带
output+="<li id=" + data.lbclassic[i]
.ageinweeks + ">"
你可以看到我的小提琴。 http://jsfiddle.net/ebilgin/34egbadn/
答案 2 :(得分:0)
您需要遍历json字符串并使用每个字符串进行迭代。 fiddle
$(document).ready(function(){
var json = {
"lbclassic": [
{
"ageinweeks": 19,
"cumul": 0.7,
"perhh": 10,
"perhd": 10,
"eggweightinweek": 45,
"eggmasscumul1": 45,
"eggmassinweek": 4.5,
"eggmasscumul": 0.03
}]};
var str = "<ul>";
$.each(json.lbclassic, function(index, element) {
str += "<li id='" + element.ageinweeks + "--" + element.cumul +"--"+element.perhh+"'> test";
str += "</li>"
});
str += "</ul>";
console.log(str);
$("#placeholder").append(str);
});