Reputation: 95
consider this json Object:
[{"data":{"ID":"3","Category":"Career"}},{"data":{"ID":"5","Category":"Emotions"}},{"data":{"ID":"1","Category":"Finance"}},{"data":{"ID":"2","Category":"Health"}},{"data":{"ID":"6","Category":"Legacy"}},{"data":{"ID":"4","Category":"Relationships"}}]
and consider this client code:
$(function (){
$.ajax({
url: 'category.php',
data: "",
dataType: 'json',
success: function(data)
{
var output = '';
$.each( data, function( key, obj) {
$.each( obj, function( index, item) {
//console.log(index+ ": " + item);
url = "goal.php?catID=" + item.ID;
output = '<li><a>' + item.Category+ '</a></li>';
href = $('a').attr("href",url); $('a').append(href);
$('#listview').append(output).listview('refresh');
});
});
}
}); });
<div data-role="page" id="home">
<div data-role="header"><h1>My Goals</h1></div>
<div data-role="listview" data-autodividers="true" data-inset="true">
<ul data-role="listview" id="listview">
</ul>
</div>
My first attempt in JQuery mobile and I am trying to loop over the JSON and output the categories with their links -
I am almost succeeding but it is only appending the last record item.ID on the url?
Can somebody please help?
Thanks
Upvotes: 1
Views: 810
Reputation: 388316
Try
$(function (){
$.ajax({
url: 'category.php',
data: "",
dataType: 'json',
success: function(data)
{
$.each( data, function( key, obj) {
var item = obj.data;
$('<li></li>').append($('<a></a>', {
text: item.Category,
href: 'goal.php?catID=' + item.ID
})).appendTo( $('#listview'))
});
$('#listview').listview('refresh');
}
});
});
Demo: Fiddle
Upvotes: 2
Reputation: 382150
When you do
$('a').attr("href",url)
You're changing all the a
elements of your page. And the last iteration wins of course.
I'd suggest you this in your loop :
$('#listview').append(
$('<li/>').append($('</a>').attr('href', url).html(url))
).listview('refresh');
Upvotes: 2