-2

我正在做 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 代码。

非常感谢。

4

1 回答 1

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+' "
    */
}
于 2012-11-06T22:23:21.227 回答