【问题标题】:Convert JSON file in <ul><li> using plain Javascript使用纯 Javascript 在 <ul><li> 中转换 JSON 文件
【发布时间】:2015-07-23 20:45:57
【问题描述】:

我的 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;
}

【问题讨论】:

  • 什么不起作用
  • 你能创建一个 JSFiddle 或代码 sn-p 以便更容易查看吗?谢谢。
  • 什么不起作用?看起来不错……
  • json 不是一个数组,它是一个对象。你应该使用for (var key in obj)
  • 那里有语法错误。 . . arr.id[i] 应该是 arr[i].id

标签: javascript html json


【解决方案1】:

Phones 必须是一个数组,并且您在其中一个数组 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;
    } 

【讨论】:

    【解决方案2】:

    试试这个

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 2021-11-14
      • 2018-11-30
      • 1970-01-01
      • 2013-01-27
      • 2022-12-16
      • 2019-05-28
      相关资源
      最近更新 更多