【问题标题】:Populating jQuery Mobile ListView with local JSON data使用本地 JSON 数据填充 jQuery Mobile ListView
【发布时间】:2016-05-09 16:18:05
【问题描述】:

我正在尝试使用本地 JSON 信息填充 JQM ListView。但是,不会创建任何列表项。任何帮助,将不胜感激。这是我的代码:

JSON 文件结构:

[
{
"name" : "test"
"calories" : "1000"
"fat" : "100"
"protein" : "100"
"carbohydrates" : "800"
},
{
"name" : "test2"
"calories" : "10000"
"fat" : "343"
"protein" : "3434"
"carbohydrates" : "4343"
}
]

HTML:

<div data-role="page" data-title="Search" id="searchPage">
      <ul data-role="listview" data-inset="true" id="searchFood">
      </ul>
</div>

JS:

(更新)

$(document).on("pageinit", "#searchPage", function(){
  $.getJSON("../JS/food.json", function(data){
        var output = '';
        $.each(data, function(index, value){
         output += '<li><a href="#">' +data.name+ '</a></li>';
        });
        $('#searchFood').html(output).listview("refresh");
  });
});

【问题讨论】:

  • $('#searchFood').html(output).listview("refresh");
  • 感谢 Omar - 但仍然没有出现这些更改的列表项:/ 我已更新帖子中的 JS 以反映您的建议。

标签: json listview jquery-mobile


【解决方案1】:

首先,返回的JSON数组是错误的,值(属性)应该用逗号隔开。

var data = [{
    "name": "test",
        "calories": "1000",
        "fat": "100",
        "protein": "100",
        "carbohydrates": "800",
}, {
    "name": "test2",
        "calories": "10000",
        "fat": "343",
        "protein": "3434",
        "carbohydrates": "4343",
}];

第二个错误,你应该读取$.each()函数返回的value对象而不是data数组。

$.each(data, function (index, value) {
  output += '<li><a href="#">' + value.name + '</a></li>';
});

jQueryMobile 只在页面加载时增强一次。当新数据被动态添加到页面时,jQueryMobile 必须知道要增强数据的数据。

JSON 数组中提取数据后,追加它们,然后 refresh listview 以重新设置新添加元素的样式。

$('#searchFood').html(output).listview("refresh");

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多