Dynamically adding <li/> to <ul/> in jquery mobile
I'm trying to add list items to unordered lists in jquery mobile, but the formatting doesn't seem to be created properly.
<ul data-role="listview" data-theme="c" data-dividertheme="b">
<li data-role="list-divider">
Title Divider
</li>
<li>
<a href开发者_如何学Go="test.html" data-transition="slide">List item 1</a>
</li>
</ul>
Script:
$('ul').append('<li><a>hello</a></li>');
For some reason the li generated dynamically doesn't display the same way as the one that's statically created. Does anyone know why and how I can make it the same?
Try this:
$('ul').append($('<li/>', { //here appending `<li>`
'data-role': "list-divider"
}).append($('<a/>', { //here appending `<a>` into `<li>`
'href': 'test.html',
'data-transition': 'slide',
'text': 'hello'
})));
$('ul').listview('refresh');
The answers provided turned out to be a little bit messy...
$('ul').append('<li><a>hello</a></li>');
is ok, but it needs to refresh the listview, so all you need is:
$('ul').append('<li><a>hello</a></li>').listview('refresh');
And if you want to change the attributes of UL, you might have to call .trigger('create') for the enclosing div. this ensures that UL is created again with properties reset.
Your <a> tag is not referencing a webpage.
try:
$('ul').append('<li><a href="test2.html' data-transition="slide" />List Item 2</li>');
You will have to add a class to the list tag
$('<ul>').append( $('<li>').attr('class','ui-li ui-li-static ui-btn-up-c ui-li-last').append('hello')) ;
JQuery mobile automatically adds a class to the list items, which can be seen if you run your page in firefox and debug it using firebug. Select whatever class has been applied and add it to your dynamically generated li tag.
精彩评论