Reputation: 47
I've been staring at this code for hours now, any input appreciated.
I want to create a list in a HTML file from an array of objects using jquery append, but it justs stays blank.
HTML:
<html>
<head>
<script src="jquery-1.10.0.js"></script>
<script src="test.js"></script>
<title></title>
</head>
<body>
<div id="list">
</div>
<div id="template">
<div class="info">
<a class="url"></a>
</div>
</div>
</body>
</html>
Script:
function update(events) {
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
}
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
Upvotes: 1
Views: 164
Reputation: 15603
Use the following JS code:
$(document).ready(function(){
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
});
Upvotes: 0
Reputation: 150010
Assuming the JS code you show is contained in test.js, either move this line:
<script src="test.js"></script>
...to the end of the body (just before the closing </body>
tag), or wrap your code in a $(document).ready()
handler.
The way you currently have it, this line:
var eventList = $('#list')
...doesn't find the '#list'
element because the script runs before the element is parsed. Same problem with finding '#template .info'
.
You could wrap all of the code in a ready handler, or if you need to be able to call the update()
function from elsewhere just wrap the initial call:
$(document).ready(function() {
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
});
Upvotes: 2