将Json转换为ul和li

时间:2014-06-05 18:35:35

标签: javascript jquery html json

我有一个看起来像这样的对象:

{
    "qA": [
        {
            "question": "How deep is the ocean",
            "answer": [
                "quite deep",
                "very deep",
                "no deep at all"
            ]
        },
        {
            "question": "How high is the sky",
            "answer": [
                "real high",
                "high enough",
                "not that high"
            ]
        }
    ]
}

我想将其加载到ul,其中问题是ul的标题,答案是li。我该怎么做?

3 个答案:

答案 0 :(得分:7)

你可以像这样使用jquery:

$.each(data.qA, function (index, item) {
    //console.log(item);
    html += "<ul>" + item.question;

    $.each(item.answer, function (index1, item1) {
        html += "<li>" + item1 + "</li>";

    });
    html+="</ul>";
});
$("#container").append(html);

FIDDLE DEMO

答案 1 :(得分:1)

您可以使用knockoutjs或任何其他模板解决方案来执行此操作。以下是您使用knockoutjs的方式。

&#13;
&#13;
var data={
    "qA": [
        {
            "question": "How deep is the ocean",
            "answer": [
                "quite deep",
                "very deep",
                "no deep at all"
            ]
        },
        {
            "question": "How high is the sky",
            "answer": [
                "real high",
                "high enough",
                "not that high"
            ]
        }
    ]
};

ko.applyBindings(data);  
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js">
</script>
<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>
    </head>
    <body>
      <div data-bind="foreach:$root.qA">
        <div data-bind="text:$data.question"></div>
        <ul data-bind="foreach:$data.answer">
          <li data-bind="text:$data"></li>
        </ul>
      </div>
    </body>
    </html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

http://www.creativebloq.com/web-design/templating-engines-9134396

我会看一下javascript模板库。这些旨在帮助您在DOM中表达您的数据。

没有模板库,你可以做一些事情。像这样脏:

function generateQuestionList(questionObject)
{

    var listContainer = document.getElementById("your-id-here");

    var heading = document.createElement("h1")

    heading.innerHTML = questionObject.question;

    var newList = document.createElement("ul");


    for(var i = 0 ; i < context.answer.length ; i ++)
        {

            var newListItem = document.createElement("li");

            newListItem.innerHTML = context.answer[i];

            newList.appendChild(newListItem);

        }

    listContainer.appendChild(heading);
    listContainer.appendChild(newList);

}