使用普通Javascript在<ul> <li>中转换JSON文件

时间:2015-05-12 19:39:36

标签: javascript html json

我有包含以下内容的JSON文件:

{
    "age": 0,
    "id": "motorola-xoom-with-wi-fi",
    "imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
    "name": "Motorola XOOM\u2122 with Wi-Fi",
    "snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
},

我需要通过使用普通的javascript以某种方式将其显示为“ul”“li”列表 我写了这段代码,但它不起作用:

function createList(){
    var arr = JSON.parse(phones);
    var out = "<ul>";
    for(var i = 0; i < arr.length;i++){
        out+="<li>" + arr[i].age + arr.id[i]+
        arr[i].imageUrl + arr[i].name + arr[i].snippet + "</li>";
    }

    out+= "</ul>";
    document.getElementById("div1").innerHTML = out;
}

2 个答案:

答案 0 :(得分:3)

手机需要是一个数组,并且您在其中一个数组derefs上有语法错误:

var phones = [{
        "age": 0,
        "id": "motorola-xoom-with-wi-fi",
        "imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
        "name": "Motorola XOOM\u2122 with Wi-Fi",
        "snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
    }];

    function createList(){
        var arr = JSON.parse(phones);
        var out = "<ul>";
        for(var i = 0; i < arr.length;i++){
            out+="<li>" + arr[i].age + arr[i].id+
            arr[i].imageUrl + arr[i].name + arr[i].snippet + "</li>";
        }

        out+= "</ul>";
        console.log(out);
        document.getElementById("div1").innerHTML = out;
    } 

答案 1 :(得分:1)

试试这个

var phones = {"age" : "0",  "id" : "motorola-xoom-with-wi-fi",  "imageUrl" : "img/phones/motorola-xoom-with-wi-fi.0.jpg",   "name" : "Motorola XOOM\u2122 with Wi-Fi",  "snippet" : "The Next Next Generation Experience the future with Motorola XOOM with Wi-Fi, the worlds first tablet powered by Android 3.0 (Honeycomb)."};

   var arr = phones;
   console.log(arr);
   var out = "<ul><li> age : " + arr.age + "</li><br><li> id : " + arr.id + "</li><br><img src='" + arr.imageUrl + "'/></li><br><li> name : " + arr.name + "</li><br><li> snippet : " + arr.snippet + "</li>"
   document.getElementById("div1").innerHTML = out;