循环遍历jQuery列表中的JSON数组

JFF*_*FFF 6 jquery json

我有这个JSON数组

// Json array
var productList = {"products": [
    {"description": "product 1", "price": "9.99"},
    {"description": "product 2", "price": "9.99"},
    {"description": "product 3", "price": "9.99"}
]
};
Run Code Online (Sandbox Code Playgroud)

我希望它循环遍历我的列表视图,但不知道如何做到这一点我所能做的就是一次列出一个项目.此外,我只能列出产品而不是产品=价格.jQuery论坛inst帮助...谢谢!

这是代码的其余部分

function loadList() {
//  var list = document.getElementById('productList');
    var list = $("#productList").listview();

    var listItem = document.createElement('li');
    listItem.setAttribute('id', 'listitem');

    listItem.innerHTML = productList.products[0].description;

    $(list).append(listItem);
    $(list).listview("refresh");
Run Code Online (Sandbox Code Playgroud)

和HTML文件

<html xmlns:f="http://www.lipso.com/f" xmlns:l="http://www.lipso.com/v2/lml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<head>
    <title>Page Title</title>
    &meta;
    <script src="@=site.cfg.resources.url@/test.js"></script>
</head>
<body onLoad="loadList()">
<div data-role="page">
    <div data-role="header" id="header">
        <h1>Dynamic Product List</h1>
    </div>
    <div data-role="content" id="content">
        <ul id="productList" data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
        </ul>
    </div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

roc*_*est 13

由于您已经在使用jQuery,为什么不使用$ .each()函数

而不是这段代码:

var listItem = document.createElement('li');
listItem.setAttribute('id', 'listitem');

listItem.innerHTML = productList.products[0].description;

$(list).append(listItem);
Run Code Online (Sandbox Code Playgroud)

用这个:

$(productList.products).each(function(index){
    $(list).append('<li id="listitem">' + this.description + " = " + this.price + '</li>');
});
Run Code Online (Sandbox Code Playgroud)