40

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="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?

locoboy
  • 38,002
  • 70
  • 184
  • 260

5 Answers5

87

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');
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • This code is slow, complicated AND the answer doesn't contain a solution - the comment does. – naugtur May 09 '11 at 11:06
  • @naugtur Hi friend, showing due respect on your comment i want to comment you that i give the solution first and it woked for cfarm54 though it finalize by comment. so why you down vote me? – thecodeparadox May 09 '11 at 11:31
  • Just to force you to update the answer. Downvote cancelled. :) All other is valid - the way you create elements is unreadable for beginners and slower than pushing a html string. Your way of adding elements is useful when more advanced methods are applied to elements - like event binding – naugtur May 09 '11 at 11:35
  • @naugtur thanks for you contructive comment.As a new user it may be fault by me and this type of advises and comments are valuable for me. Thanks again. – thecodeparadox May 09 '11 at 11:38
  • @abdullah.abcoder I'm glad you look at it that way. +1 for attitude! Good luck. – naugtur May 09 '11 at 12:39
  • This is the right answer no matter what, i've stuggleling with this issue forever and ever.... – Friis1978 May 31 '15 at 12:40