Brian
Brian

Reputation: 4418

How do I get jquery to pick up dynamically added dom with jquery mobile

I have a function in a jquery mobile app that fetches data via post and populates a list view. Like this

 function updateSomething(data){
            var list =  $('#list');

            $.each(data.comments, function(key, comment) { 

                var item = '<li data-theme="c"> <a data-icon="arrow-r" class="test" href="# id="'+comment.id+'"><h3>'+comment.data+'</h3></a></li>';

                //update the current dom with list items
                list.append(item);
            });

            list.listview('refresh');   
        }

is there some way to have jquery refresh the dom or something once I update it dynamically?

This should be picked up by the following javascript but it isnt

<script type='text/javascript'>
 $("#comment_page").live('pageinit', function() {
             $('.test').click(function() {

                 alert('test click');
             });
       });

</script>

html

 //comment page
<div data-role="page" id="comment_page" data-theme="c">
        <div data-role="content"> 
            <ul data-role="listview" id="list" data-theme="b"></ul> 
        </div> 
    </div>

  //another page
  <div data-role="page" id="login_page" data-theme="b">

        <div data-role="header">
            <h1>Login</h1>
        </div><!-- /header -->

        <div data-role="content">


            <div id="response"></div>

            <div data-role="fieldcontain" class="ui-hide-label">
                <label for="email">Email:</label>
                <input type="text" name="email" id="email" value="" placeholder="Email"/>
            </div>

            <div data-role="fieldcontain" class="ui-hide-label">
                <label for="password">password:</label>
                <input type="password" name="password" id="password" value="" placeholder="Password"/>
            </div>

            <input type="submit" name="login_button" id="login_button" value="Login"/>


        </div><!-- /content -->


    </div><!-- /page -->

Upvotes: 0

Views: 466

Answers (1)

TommyBs
TommyBs

Reputation: 9648

Try changing your .click to .live("click", function(){ //your code

The other option is using the delegate method on a dom element that already exists and that isn't getting added by jQuery

<script type='text/javascript'>
 $("#comment_page").live('pageinit', function() {
         $('.test').live("click",function() {

             alert('test click');
         });
   });

</script>

Upvotes: 1

Related Questions