将所有JSON值放入单独的<div>中

时间:2017-02-20 10:33:15

标签: javascript html json

我对JSON很陌生。我想要做的是我有JSON,其中包含3个对象,我想将每个对象放入其各自的(那里有3个div)。下面的代码不会向

添加任何内容

HTML:

    var testwrapper= $("<div/>").addClass("testwrapper").appendTo(somethingwrapper);
    var test1wrapper= $("<div/>").addClass("test One").appendTo(testwrapper);
    var test2rapper= $("<div/>").addClass("test Two").appendTo(testwrapper);
    var test3wrapper= $("<div/>").addClass("test Three").appendTo(testwrapper);

    <div class="Test One"></div>
    <div class="Test Two"></div>
    <div class="Test Three"></div>

JSON:

function dummytestJSON(){
         testJSON = {
            "Test" : 
            [
                {
                    "img" : "../img/test1.png",
                    "title" : "Test1",
                    "description" : "you have notification",
                    "time" : "2 mins ago"
                },
                {
                    "img" : "../img/test2.png",
                    "title" : "Test2",
                    "description" : "you have alerts",
                    "time" : "4 mins ago"
                },
                {
                    "img" : "../img/test3.png",
                    "title" : "Test3",
                    "description" : "you have notifications",
                    "time" : "9 mins ago"
                }
            ]
        };  
        //console.log(testJSON .Test_);
        return JSON.stringify(testJSON );
    }

脚本:

function updateTest(){
    console.log("updating test");
    //console.log(testJSON);
    dummytestJSON();
    var testwrapper = ["Test One","Test Two","Test Three"];
    for(var test in testJSON.Test_){
        console.log(testJSON.Test_[test].title);

        var text = $("<p/>").text(testJSON.Test_[test ].title).appendTo("#"+testwrapper [test ]);

    }

}

2 个答案:

答案 0 :(得分:1)

我看到了这些更正:

方法dummytestJSON(),需要返回干净的JSON,返回testJSON;

方法updateTest:

function updateTest(){
    console.log("updating test");
    //console.log(testJSON);
    var Test_ = dummytestJSON();
    var testwrapper = ["Test One","Test Two","Test Three"];
    for(var test in Test_){
        console.log(Test_[test].title);

        var text = $("<p/>").text(Test_[test ].title).appendTo("#"+testwrapper [test ]);

    }

}

答案 1 :(得分:0)

尝试:

<div class="Test One" id="div_1"></div>
<div class="Test Two" id="div_2"></div>
<div class="Test Three" id="div_3"></div>

然后使用

document.getElementById('div_1').innerHTML = ... 

设置内容。