Динамическое добавление элементов в jQuery Mobile ListView - PullRequest
7 голосов
/ 01 ноября 2011

Я хочу динамически добавлять данные, полученные через URL в формате JSOn, в мой список. Но я не могу понять, как это работает.

Мобильный веб-сайт получает объект в следующем формате:

[
    {"id":1, "start":"2011-10-29T13:15:00.000+10:00", "end":"2011-10-29T14:15:00.000+10:00", "title":"Meeting"}
]

В .html у меня есть один просмотр списка и функция, где я пытаюсь добавить полученные данные. Я показываю только тело.

<body>
       <div>   
            <ul id="listview">
                <script>$.getJSON("url",
                function(data){
                    $.each(data, function(i,data){
                        i.title.appendTo("#listview");
                    });});</script> 
            </ul>
        </div>
</body>

Возможно, это очень просто, но я новичок в веб-программировании и не могу понять, как мне добавить полученные данные.

Может кто-нибудь помочь мне?

Ответы [ 5 ]

20 голосов
/ 01 ноября 2011
//make AJAX call to url
$.getJSON("url", function(data){

    //declare a variable with which to build our output (it's best to buffer output and only do one append at the end since DOM manipulation is CPU expensive)
    var output = '';

    //iterate through the data (we could also get rid of the jQuery here by using `for (key in data) {
    $.each(data, function(index, value){

        //add each value to the output buffer (we also have access to the other properties of this object: id, start, and end)
        output += '<li>' + value.title + '</li>';
    });

    //now append the buffered output to the listview and either refresh the listview or create it (meaning have jQuery Mobile style the list)
    $('#listview').append(output).listview('refresh');//or if the listview has yet to be initialized, use `.trigger('create');` instead of `.listview('refresh');`
});

Вот jsfiddle вышеупомянутого решения (есть также пример использования for(){} вместо $.each()): http://jsfiddle.net/VqULm/

1 голос
/ 26 марта 2013

Я добавляю вот так ... Он работает для добавления ... Это может быть полезно для вас или других:)

          $.each(data.values, function(key, value) {

          $('#activity_contacts').append('<li id="activity_contacts" data-id="' + value.contact_id + '">' + value.display_name + '</li>');
          $("#activity_contacts").listview("refresh");


          });

Все мое автозаполнение выглядит так:

    function contactSearchForActivities (q) {
    $.mobile.showPageLoadingMsg( 'Searching' );
    $().crmAPI ('Contact','get',
      {'version' :'3', 'activity_sort_name': q, 'return' : 'display_name' },
      {
        ajaxURL: crmajaxURL,
        success:function (data){
          if (data.count == 0) {
            cmd = null;
          }
          else {
            cmd = "refresh";
            $('#activity_contacts').show();
            $('#activity_contacts').empty();
          }
          //console.log(data);

          //loop to go through the values in order to display them in a li as a list


          $.each(data.values, function(key, value) {

          $('#activity_contacts').append('<li id="' + value.contact_id + '" title = "' + value.display_name +'">' + value.display_name + '</li>');

   }); 

   $("#activity_contacts li").click(function() {

   $('#activity_sort_name').val(this.title);
   $('#activity_hidden_id').val(this.id);
           $("#activity_contacts").empty();
   });

          $.mobile.hidePageLoadingMsg( );
          $('#activity_contacts').listview(cmd);
        }
      });
  } 
0 голосов
/ 09 марта 2014

Если вы пытаетесь воссоздать просмотр списка, вам нужно .trigger (создать) и .listview (обновить) список.Проблема объяснена на http://liljosh.com/jquery-mobile-dynamicly-appending-to-listview-via-ajax-issue/

0 голосов
/ 04 января 2012

Пожалуйста, обновите список после добавления или удаления.Если вы не освежитесь, ничего не будет видно.

$('#listview').append(output).listview('refresh');
0 голосов
/ 01 ноября 2011

Я думаю, что проблема, с которой вы можете столкнуться, заключается в том, что возвращаемый JSON - это объект , заключенный в массив . Для разбора вам придется сначала пройтись по массиву:

for( var x = 0; x < data.length; x++ ) {
 var i = data[ x ];
 i.title.appendTo("#listview");
}
...