0

我的代码有问题。我正在创建新的 div,然后将它们插入到每个具有timeand类的元素之前time2。不幸的是我的代码不起作用我得到 insertBefore is undefined 错误。我怀疑它是我的 for 循环,但我需要进一步的帮助。

window.onload = function () {
    var badges, timeOne, timeTwo, parentDiv;

    timeOne = document.getElementsByClassName("time");
    timeTwo = document.getElementsByClassName("time2");

    for (index = 0; index < timeOne.length; ++index) {
        badges = document.createElement("div");
        badges.id = "badges";
        parentDiv = timeOne.parentNode;
        parentDiv.insertBefore(badges, timeOne[index]);
    }

    for (index = 0; index < timeTwo.length; ++index) {
        badges = document.createElement("div");
        badges.id = "badges";
        parentDiv = timeTwo.parentNode;
        parentDiv.insertBefore(badges, timeTwo[index]);
    }
}
4

1 回答 1

0

timeOne不是元素而是数组,所以它没有parentNode.

您可能想使用

parentDiv = timeOne[index].parentNode;
parentDiv.insertBefore(badges, timeOne[index]); 

为避免这些错误,我建议您为变量提供更有意义的名称。例如

var timeOneElements = document.getElementsByClassName("time");
于 2012-07-11T07:26:02.287 回答