需要知道如何使用jQuery / JS将这段JSON转换成HTML

时间:2010-08-12 06:24:00

标签: javascript json

我需要知道如何使用jQuery将以下JSON放入类名为article的元素中,并使用一些基本的JavaScript:

{"elements": [
    {
        "head": "story 1",
        "writer": "journalist 1"
    },
    {
        "head": "story 2",
        "writer": "journalist 2"
    }
]}

尝试实现以下HTML。我是JSON等人的新手。想要通过示例来学习..

<div class="article">
    <h5>story 1</h5>
    <p>By: journalist 1</p>

    <h5>story 2</h5>
    <p>By: journalist 2</p>
</div>

2 个答案:

答案 0 :(得分:3)

var data = {
    "elements": [
        {
            "head": "story 1",
            "writer": "journalist 1"
        },
        {
            "head": "story 2",
            "writer": "journalist 2"
        }
    ]};

var result = []; /* where we will store the generated HTML */

$.each(data.elements, function() {
    /* in this function, `this` refers to one of the [story] objects in the elements array */
    result.push('<h5>');
    result.push(this.head);
    result.push('</h5><p>By: ');
    result.push(this.writer);
    result.push('</p>');
});

$('<div class="article" />') /* creates the div class="article" */
    .html(result.join('')) /* merges the generated HTML from above and inserts it into the div*/
    .appendTo(document.body); /* appends the div to the page */

答案 1 :(得分:1)

使用jQuery非常简单。使用追加功能:

var jsonObj = {"elements": [
    {
        "head": "story 1",
        "writer": "journalist 1"
    },
    {
        "head": "story 2",
        "writer": "journalist 2"
    }
]};

var article = $(".article");
var items = jsonObj["elements"];

var arr = [];    

for(var i = 0, len = items.length; i < len; i++)   {
   var itm = items[i];
   arr.push("<h5>" + item["head"] + "</h5><p>By: " + item["writer"] + "</p>");
}

article.append(arr.join(""));