【问题标题】:How can i append all the elements of an array to a div [closed]如何将数组的所有元素附加到 div [关闭]
【发布时间】:2017-07-10 01:54:53
【问题描述】:

下面显示了我当前的来源是什么,但这似乎只是将我数组中的最后一个对象添加到我的 div 中,我怎样才能将所有对象添加到我的 div 中。

    ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) => {
        console.log(response);
        var divVehicles = <HTMLDivElement>document.getElementById("divVehicleResults");
        var label = <HTMLLabelElement>document.createElement("label");
        for (let vehicle of response) {
            label.innerHTML = vehicle.id;
            divVehicles.appendChild(label);
        }
    });

【问题讨论】:

  • 这是因为你重复使用了同一个标签对象。您需要在循环中使用var label = ...
  • 啊,很好发现,为我整理了谢谢,你可以把它放在答案中,这样我就可以标记它@approxiblue
  • @ifelabolz 完成

标签: javascript html arrays typescript appendchild


【解决方案1】:

正如 approxiblue 所说,现在您正在重用相同的标签对象。您应该将var label = ... 放入循环中以每次创建一个新标签(从而按照您的要求附加新标签)。

更正的代码:

ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) => {
    console.log(response);
    var divVehicles = <HTMLDivElement>document.getElementById("divVehicleResults");

    for (let vehicle of response) {
        var label = <HTMLLabelElement>document.createElement("label");
        label.innerHTML = vehicle.id;
        divVehicles.appendChild(label);
    }
});

【讨论】:

    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 2021-04-18
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2021-07-04
    相关资源
    最近更新 更多