Reputation: 2697
I'm trying to increment through JQuery loop to fill out some HTML code with data from a JSON file. The problem is that I can't seem to figure out how to get write the divs to the HTML below one another, instead the loop increments the data over each other and finally shows the last object in the array on the screen.
Here is my Javascript (tubing.js):
$(document).ready(function() {
crazyFun();
});
function crazyFun() {
for (var i = 0; i < virtualGoods.length; i++) {
var alpha= $('div.container').clone();
alpha.find('div.picture').attr('id', virtualGoods[i].picture);
alpha.find('h2').html(virtualGoods[i].header);
alpha.find('p').html(virtualGoods[i].text);
alpha.find('div.notification').attr('id', virtualGoods[i].notification);
$('div.container').append(alpha);
}
}
}
"Container" is the HTML Div that I want to repeat on my page with the filled in JSON data.
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World</title>
<link rel="stylesheet" type="text/css" href="iphone.css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="virtualgoods.js"></script>
<script type="text/javascript" src="tubing.js"></script>
</head>
<body>
<div id="mainhead">
<h1>
Hello World
</h1>
</div>
<div id="repeater">
<div class="container">
<div class="picture">
</div>
<div class="object">
<div class="header">
<h2></h2>
</div>
<div class="text">
<p>
</p>
</div>
</div>
<div class="notification">
</div>
<div class="neg">
</div>
</div>
</div>
<div id="buffer">
</div>
</body>
</html>
Upvotes: 2
Views: 2402
Reputation: 19601
3 things jump out at me:
$('container')
isn't selecting your div with id="container"
, it's looking for a <container>
element. Try changing this to $('#container')
.alpha
, but your not do any data work to it. Try doing this pattern: alpha.find('div.picture').attr('id', virtualGoods[i].picture);
. Now you are editing the div in the cloned alpha div..after()
instead of append. This will insert alpha
in the DOM after container
, not inside it.Hope this helps!
EDIT:
Ok, your almost there. just a couple of changes to go.
$('div.container').append(alpha);
to $('#repeater').append(alpha);
. This will mean that your appending the new, cloned div after the other one, not inside it..container
). What you need to do is either give the first one a unique id such as id="template"
and select on that when you clone or remove the class attribute off your cloned div (use .removeClass()
.Upvotes: 4