Creating and modifying lists with jQuery Mobile?
This concerns jQuery Mobile 1.0 Beta 1
I love jQuery Mobile but for the love of god I can't figure out how to dynamically add list items. I first tried without binding the pagebeforecreate event -- the items were appended to DOM but were not visible, even tho I tried calling many combinations of the following:
$("#categories").listview();
$("#categories").listview('refresh');
$("#categories").listview('refresh', true);
I was getting "Result of expression 'b[0]' [undefined] is not an object." error.
I then figured that I could bind to page开发者_C百科beforecreate event to append the li-items before jQuery Mobile does its magic. However, this doesn't help.. same result as before.
$().ready(function() {
$("#browse-categories").live('pagebeforecreate', function() {
$.get('http://foo.com/api/categories.xml', function(data) {
$xml = $(data);
$xml.find('entry').each(function() {
$("#categories").append("<li>" + $(this).find('title').text() + "</li>")
});
});
});
});
The HTML:
<div data-role="page" id="browse-categories">
<div data-role="header">
<h1>Categories</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="categories">
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
So what the heck?
I have this working in the last alpha release, but haven't tested it in beta 1. I have a page event script thus (remember, it has to come before the jQuery Mobile src is referenced):
$('#YOUR-PAGE-ID').live('pageshow',function(event, ui){
someFunction();
});
... and the referenced someFunction
contains code similar to this:
var list = $("#categories");
list.empty();
$.each(results.rows, function(rowIndex){
// I actually do way more than this; simplified for example
var data = results.rows.item(rowIndex);
list.append("<li>"+data+"</li>");
});
list.listview('refresh');
Does that help at all? The refresh
is crucial, as is the placement of the script to trigger it.
I had the same issue, this worked for me:
In doc ready, create the dynamic LI without calling the .listview() on it, then hook into the pagebeforeshow event and call the listview() once :
$("#ModeList").bind("pagebeforeshow", function() {
$("#ModeList ul").listview();
$(this).unbind('pagebeforeshow');
});
Correction, this works better. Bottom line is you need a slight delay before the refresh:
$(document).bind("pagebeforechange", function( e, data ) {
urlObj = $.mobile.path.parseUrl(data.toPage);
if (typeof data.toPage === "string")
{
if (page_name == "#pgMode" ) {
$("#ModeList").html("");
setTimeout(function() {
$("#ModeList ul").listview();
}, 1);
}
}
});
精彩评论