小编典典

动态添加元素到jQuery Mobile ListView

ajax

我想将通过JSOn格式的URL接收的数据动态附加到我的列表视图中。但是我不知道它是如何工作的。

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

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

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

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

也许这很容易,但是我是Web编程的新手,我不知道该如何附加检索到的数据。

有人可以帮我吗?


阅读 233

收藏
2020-07-26

共1个答案

小编典典

//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/
2020-07-26