【发布时间】:2016-10-21 21:25:16
【问题描述】:
我有一个 JSON 数组和一些 JavaScript,但循环没有执行。
我找不到错误。
HTML:
<div class="rosa" id="Mittelt">
// place to append
</div>
JavaScript:
$(function() {
var url = {"cats": [
{"id":"1",
"pictures":"http://www.w3schools.com/css/img_fjords.jpg",
"picsmall":"http://www.w3schools.com/css/img_fjords.jpg"},
{"id":"2",
"pictures":"http://www.w3schools.com/css/img_lights.jpg",
"picsmall":"http://www.w3schools.com/css/img_lights.jpg"}
]
};
var json=url["cats"];
$(json).each(function(item) {
console.log(json[0].id);
item=json[0];
$('<div class="lulu">' +
'<img src="http://www.w3schools.com/css/img_fjords.jpg" data-src="'+item.pictures+'.jpg"/>' +
'<img class="lora" src="'+item.picsmall+'"/>'+'</div>')
.appendTo('#Mittelt');
})
CSS:
.lulu {
position:absolute;
height:100%;
-webkit-transform: translateZ(0px);
-ms-transform: translateZ(0px);
-o-transform: translateZ(0px);
transform: translateZ(0px);
}
.lora {
position:absolute;
height:50%;
-webkit-transform: translateZ(0px);
-ms-transform: translateZ(0px);
-o-transform: translateZ(0px);
transform: translateZ(0px);
}
【问题讨论】:
-
您正在覆盖
item,因此它始终指向第一个元素:item=json[0];删除该行。 -
我在小提琴上试过。但这不是错误:-(
-
还将
$(json).each(function(item){更改为$(json).each(function(i, item){ -
@Viktor 你让我开心:-),谢谢。但现在我尝试了 3 个 id,它在第二个之后停止。你能看看吗? jsfiddle.net/5wyL5azj/6
-
这只是由于您的 CSS 样式。如果您使用开发者工具或类似工具检查呈现的 HTML,您可以看到所有三个
divs 及其内容都在那里。
标签: javascript jquery json loops foreach