读取不同div中的JSON数据

时间:2015-03-22 10:14:49

标签: javascript jquery json

我对此非常陌生。计划是在不同的div中显示来自JSON文件的数据,因为我想以不同的方式设置div的样式。

1)首先,我想读出一行JSON,例如:

HTML:

<div>
    <div data-filter="EX_01_Dates"></div>
    <div data-filter="EX_01_Name"></div>
    <div data-filter="EX_01_City"></div>
</div>

JSON:

var data={"events":[
        {
            "id": EX_01,
            "Name":"Event 1",
            "City":"City 1",
            "Dates":"13-09-2015",
        },
]}

2)其次,我想用不同的数据块。

var data={"events":[
        {
            "id": EX_01,
            "Name":"Event 1",
            "City":"City 1",
            "Dates":"13-09-2015",
        },
        {
            "id": EX_02,
            "Name":"Event 2",
            "City":"City 2",
            "Dates":"15-09-2015",
        }
]}

这就是我的jsfiddle。希望有人可以帮助我?

3 个答案:

答案 0 :(得分:0)

我强烈建议你为此目的使用 jsrender ,有很多关于它的好文章。我发现下面的文章非常有用,如果你不理解http://www.jsviews.com希望这有帮助..

https://msdn.microsoft.com/en-us/magazine/hh882454.aspx

答案 1 :(得分:0)

首先,目前尚不清楚你到底在做什么。

<div id="EX_01">
    <div data-filter="EX_01_Dates"></div>
    <div data-filter="EX_01_Name"></div>
    <div data-filter="EX_01_City"></div>
</div>

<div id="EX_02">
    <div data-filter="EX_02_Dates"></div>
    <div data-filter="EX_02_Name"></div>
    <div data-filter="EX_02_City"></div>
</div>

您的javascript代码现在已添加jquery

    var data={"events":[
        {
            "id": EX_01,
            "Name":"Event 1",
            "City":"City 1",
            "Dates":"13-09-2015",
        },
        {
            "id": EX_02,
            "Name":"Event 2",
            "City":"City 2",
            "Dates":"15-09-2015",
        }
]}

$("#EX_01").find("div:nth-child(1)").html(data.events[0].Dates);
$("#EX_01").find("div:nth-child(2)").html(data.events[0].Name);
$("#EX_01").find("div:nth-child(3)").html(data.events[0].City);

$("#EX_02").find("div:nth-child(1)").html(data.events[1].Dates);
$("#EX_02").find("div:nth-child(2)").html(data.events[1].Name);
$("#EX_02").find("div:nth-child(3)").html(data.events[1].City);

你可以更多地动态创建或选择html元素

答案 2 :(得分:0)

这样的东西?

var data={"events":[
    {"id": "EX_01", "Name":"Event 1", "City":"City 1", "Dates":"13-09-2015" },
    {"id": "EX_02", "Name":"Event 2", "City":"City 2", "Dates":"15-09-2015" }
]};

data["events"].forEach(function(elem) {
    for(var key in elem) {
        var filter = [elem["id"], "_", key].join("");
        $("div[data-filter='" + filter + "']").text(elem[key]);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
	<div data-filter="EX_01_Dates"></div>
    <div data-filter="EX_01_Name"></div>
    <div data-filter="EX_01_City"></div>
</div>

<div>
	<div data-filter="EX_02_Dates"></div>
    <div data-filter="EX_02_Name"></div>
    <div data-filter="EX_02_City"></div>
</div>

了解Array forEachfor...in,了解它们的工作原理!