1

我在 javascript 变量中有 json 字符串。我想从 JSON 字符串中获取随机值并设置为 HTML。

var jsonContent= {
          "featured": [
            {
              "id": "111",
              "title": "post title 111",
              "desc": "This is a test desc 111"
            },
            {
              "id": "222",
              "title": "post title 222",
              "desc": "This is a test desc 222"
            },
            {
              "id": "333",
              "title": "post title 333",
              "desc": "This is a test desc 333"
            }
    ]
};

例如,第一个键值分配给我的 html,如下所示:-

   <div class="r-v-details">
    <span class="r-v-title">post title 111</span>
    <span class="r-v-description">This is a test desc 222</span>
   </div>

如何从 JSON 字符串中获取随机键值?我是否需要将 JSON 解析为数组然后才能获得随机值?或者我只能通过 json 来实现?你能建议我吗?

4

2 回答 2

7

它应该是:(在控制台中检查结果)

var jsonContent = {
        "featured": [
            {
                "id": "111",
                "title": "post title 111",
                "desc": "This is a test desc 111"
            },
            {
                "id": "222",
                "title": "post title 222",
                "desc": "This is a test desc 222"
            },
            {
                "id": "333",
                "title": "post title 333",
                "desc": "This is a test desc 333"
            }
        ]
    }

    var random = jsonContent.featured[Math.floor(Math.random() * jsonContent.featured.length)];
    console.log(random)
于 2013-10-25T12:29:11.090 回答
3

试试这个:

var random = jsonContent["featured"][Math.floor(Math.random()*jsonContent["featured"].length)];
于 2013-10-25T12:24:45.870 回答