将元素动态附加到 jQuery Mobile ListView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7961108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:32:00  来源:igfitidea点击:

Dynamically Appending Elements to jQuery Mobile ListView

jqueryajaxjsonjquery-mobile

提问by Jo?o Nunes

I want to dynamically append data received via an url in JSOn format to my listview. But i can't figure out how it works.

我想将通过 JSOn 格式的 url 接收到的数据动态附加到我的列表视图。但我无法弄清楚它是如何工作的。

The mobile website retrieve the object in the following format:

移动网站按以下格式检索对象:

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

In the .html i have one listview and a function, where i try to append the received data. I show only the body.

在 .html 中,我有一个列表视图和一个函数,我尝试在其中附加接收到的数据。我只展示身体。

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

Probably it's very easy, but i'm new to web programming and i can't figure out how that i should append the retrieved data.

可能这很容易,但我是网络编程的新手,我不知道应该如何附加检索到的数据。

Can anyone please help me out ?

任何人都可以帮我吗?

回答by Jasper

//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');`
});

Here is a jsfiddle of the above solution (there is also an example of using for(){}instead of $.each()): http://jsfiddle.net/VqULm/

这是上述解决方案的 jsfiddle(还有一个使用for(){}代替的示例$.each()):http: //jsfiddle.net/VqULm/

回答by Developer

I'm appending like this..Its working for appending.. It may be helpful for you or others :)

我是这样附加的..它可以用于附加..它可能对您或其他人有帮助:)

          $.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");


          });

My entire autocomplete is like this:

我的整个自动完成是这样的:

    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);
        }
      });
  } 

回答by Josh LaMar

If you're trying to recreate a listview then you'll need to .trigger(create) and .listview(refresh) the list. The issue is explained at http://liljosh.com/jquery-mobile-dynamicly-appending-to-listview-via-ajax-issue/

如果您尝试重新创建列表视图,则需要 .trigger(create) 和 .listview(refresh) 列表。该问题在http://liljosh.com/jquery-mobile-dynamicly-appending-to-listview-via-ajax-issue/ 中有解释

回答by buley

I think the issue you might be encountering is that the JSON being returned is an object wrapped in an array. To parse you will have to iterate through the array first:

我认为您可能遇到的问题是返回的 JSON 是一个包裹在数组中的对象。要解析,您必须首先遍历数组:

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

回答by shyamshyre

Please refresh the listview after appeding or removing. Unless you do refresh nothing can be seen.

应用或删除后请刷新列表视图。除非你刷新,否则什么都看不到。

$('#listview').append(output).listview('refresh');