javascriptjquerycordovajquery-mobilevisual-studio-cordova

Problems adding dynamic data to UL jquery mobile


I have this ul

  <ul data-role="listview" id="contributionList" data-split-icon="delete" data-split-theme="d">
    <li id="l1"><a>5.00</a><a id="1" class="deleteMe"></a></li>
    <li><a>10.00</a><a class="deleteMe"></a></li>                        
  </ul>

I'm trying to add data dynamically to it. But for reasons I don't understand, it doesn't take the class deleteme.

This is how I'm trying to fill it:

 $('#OkTarget').bind("click tap", function () {        
     $('#contributionList').append('<li id="lii1"><a>5.00</a><a id="aid1" class="deleteMe"></a></li>').listview('refresh');                       
 });

This is what is supossed to be done when it click:

$('.deleteMe').bind("click tap", function () {
    $(this).parent().remove();
    $('#contributionList').listview('refresh');
}); 

Solution

  • You need to delegate for elements added dynamically. Try

    $(document).on('click tap', '.deleteMe', function () {
        $(this).parent().remove();
        $('#contributionList').listview('refresh');
    }); 
    

    instead of

    $('.deleteMe').bind("click tap", function () {
        $(this).parent().remove();
        $('#contributionList').listview('refresh');
    }); 
    

    bind will attach events to only existing elements with that selector when it is executed