在Ajax请求上动态创建Div

时间:2015-08-04 17:15:43

标签: javascript loops

我试图在AJAX请求时动态创建几个div。我能够创建它们,但是我的for循环出了问题:

for (var i = 0; i < data.stylist_1.length; i++) {

    stylist1Addresses.push(data.stylist_1[i]);

    for (x = 0; x < stylist1Addresses.length; x++) {
        var temp = document.createElement("div");
        temp.className = "unit";
        temp.innerHTML = stylist1Addresses[i].Address;
        document.getElementById("list").appendChild(temp);
    }
}

正如您在此JSFiddle(http://jsfiddle.net/joptmqh8/)中所看到的,它创建了6个div。为什么?它应该只创建stylist_1对象中前3个地址的div。

4 个答案:

答案 0 :(得分:3)

你的for循环应该是单独的:

var stylist1Addresses = [];

for (var i = 0; i < data.stylist_1.length; i++) {
    stylist1Addresses.push(data.stylist_1[i]);
}
for (x = 0; x < stylist1Addresses.length; x++) {
        var temp = document.createElement("div");
        temp.className = "unit";
        temp.innerHTML = stylist1Addresses[x].Address;
        document.getElementById("list").appendChild(temp);
    }
console.log(stylist1Addresses);

答案 1 :(得分:2)

只需删除内循环:

var data = {
    "stylist_1": [{
        "Address": "1 Stn Main",
            "Phone": "403-990-9033"
    }, {
        "Address": "474 Cirrus Rd",
            "Phone": "403-995-3243"
    }, {
        "Address": "1591 Stn St",
            "Phone": "403-982-8893"
    }],
        "stylist_2": [{
        "Address": "219 Welch Blvd",
            "Phone": "587-436-3171"
    }, {
        "Address": "374 Main Rd",
            "Phone": "587-315-9431"
    }, {
        "Address": "564 Main Rd",
            "Phone": "403-938-9983"
    }]
}

var stylist1Addresses = [];

for (var i = 0; i < data.stylist_1.length; i++) {
    stylist1Addresses.push(data.stylist_1[i]);

    var temp = document.createElement("div");
    temp.className = "unit";
    temp.innerHTML = stylist1Addresses[i].Address;
    document.getElementById("list").appendChild(temp);
}
console.log(stylist1Addresses);
.unit:nth-child(odd) {
    background: rgba(0, 0, 0, 0.05);
}
<div id="list"></div>

答案 2 :(得分:1)

那是因为你的内循环正在为外循环的每次迭代执行。

你看到1,2&amp; thenRlement的3个实例,因为在内部循环中,要追加的元素由itemp.innerHTML = stylist1Addresses[i].Address;)指定,附加x次。

更正小提琴:http://jsfiddle.net/joptmqh8/2/

答案 3 :(得分:0)

更新了你的jsfiddle here http://jsfiddle.net/1qdn55v3/。 一旦你推动了 stylist1Addresses 中的所有地址,就关闭for循环并再创建一个for循环来创建div