Reputation: 2084
I'm trying to dynamically create a navbar from data i fetch from a web api serving json data. Here's the code: https://gist.github.com/2962277 If i use:
<div data-role="navbar">
<ul>
<li><a href="a.html">One</a></li>
<li><a href="b.html">Two</a></li>
</ul>
</div>
directly in html code works fine, but this is not what im looking for. I want to be able to create the list elements from the data in the like the code in gist show. Anyone could point me in the right direction?
Upvotes: 0
Views: 6155
Reputation: 1049
I was having the same problem (I'm regenerating my navbar all the time, depending on the fetched data) and my solution has been the following:
var navBar = '<div id="invNavBarAction" data-role="navbar" data-iconpos="left"><ul>';
navBar += '<li>MANY LINES AS YOU NEED</li>';
navBar += '</ul></div>';
$('#invNavBarAction').remove();
$('#invNavBarContainer').append($(navBar));
$('#invNavBarAction').navbar();
HTML:
<div id="invNavBarContainer">
<div id="invNavBarAction" data-role="navbar" data-iconpos="left"></div>
</div>
Upvotes: 0
Reputation: 76003
Once you have concocted your HTML for the navbar widget, you simply call .trigger('create')
on the widget:
var myNavbar = $('<div data-role="navbar"><ul><li><a href="a.html">One</a></li><li><a href="b.html">Two</a></li></ul></div>');
$('#some-container').append(myNavbar).trigger('create');
Here is a demo: http://jsfiddle.net/Jde95/
This will trigger jQuery Mobile to initialize the widget.
For Example:
var url = "http://23.21.128.153:3000/regions.json";var jsonresults;
$.getJSON(url,function(data){
var output = [];
$.each(jsonresults, function(i,v){
output.push('<li><a href="' + jsonresults[i].link + '">' + jsonresults[i].name + '</a></li>');
});
$('#main-content').append('<div data-role="navbar">' + output.join('') + '</div>').trigger('create');
});
Notice how I concocted the HTML, and used the .append()
function.
Upvotes: 4