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 に答える