Javascript函数将对象数组转换为HTML

时间:2012-11-06 21:26:01

标签: javascript html css web

我正在做和Web应用程序,我需要实现一个函数,将javascript中的这个对象数组转换为HTML中的“ul”,但我不知道,所以也许你可以帮助我...

我将任务项保存在数据库中,这是我从DB调用GET函数时数据库给出的结果:

{"code": "ok", "data": [
        {"done": 1, "deadline": "2012-11-09", "id": 1, "desc": "Go to run"}, 
        {"done": 0, "deadline": "2012-11-09", "id": 2, "desc": "Go to doctor"}, 
        {"done": 0, "deadline": "2012-11-08", "id": 3, "desc": "Go to buy"}
]}

我必须将每个任务对象放在HTML“ul”中,如下所示:

<ul>
<a href="#dialog"><li data-task-id="1">
    <p class="desc">Go to run</p>
    <time datetime="2012-11-09">09/11/2012</time>
    <p class="done" data-task-done="yes">done</p>
</li></a>

<a href="#dialog"><li data-task-id="1">
    <p class="desc">Go to doctor</p>
    <time datetime="2012-11-09">09/11/2012</time>
    <p class="done" data-task-done="yes">done</p>
</li></a>

<a href="#dialog"><li data-task-id="2">
    <p class="desc">Go to buy</p>
    <time datetime="2012-11-09">09/11/2012</time>
    <p class="done" data-task-done="no">not done</p>
</li></a>

我需要一个JavaScript函数来从数组创建这个html代码。

非常感谢。

1 个答案:

答案 0 :(得分:1)

你需要迭代数组

var arr = YOUR_DATA.data;
var code = "";
for ( var i=0; i < arr.length; i++) {
    // This is called for every Item

    var currentItem = arr[i];
    // This is your Item

    code += '<a [...] <p class="desc">' + currentItem.desc + '</p> [...]'
    /*
        Just replace the brackets and write your HTML Code in there
        If there is a variable write " '+currentItem.VAR_NAME+' "
    */
}