JS DOM追加子项不起作用

JS DOM append child does not work

本文关键字:不起作用 追加 DOM JS      更新时间:2023-09-26

我正在尝试实现一个简单的函数,该函数获取一些元素列表(在本例中,我传递一些<li>元素),并将它们按随机顺序附加到某个父节点(<ul>)。为了做到这一点,我写了这样的东西:

console.log(tmpList);
var maxIndex = tmpList.length;
while(tmpList.length > 0) {
    var curIndex = Math.floor(Math.random() * maxIndex);
    if(tmpList[curIndex] && tmpList[curIndex].nodeType===1) {
        var elem = tmpList.splice(curIndex, 1);
        console.log(elem);
        parent.appendChild(elem);
    }
}

正如你所看到的,我确实检查了随机选择的索引是否真的仍然存在于tmpList中,以及它是否真的是html元素。然而,当我运行此代码时,我得到:

[li, li, li, li]
[li]
NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.

我做错了什么?

ps。请不要给我诸如"使用jquery"或"使用innerHTML连接它"之类的建议,因为我不能使用它们是有原因的。

[edit]parent元素是在几行之前定义的,所以情况并非如此。

更新

我根据一个答案做了一些更改,所以代码看起来如下:

while(tmpList.length > 0) {
    var curIndex = Math.floor(Math.random() * tmpList.length);
    var elem = tmpList.splice(curIndex, 1);
    console.log(elem);
    if(elem instanceof HTMLElement) {
        //console.log(curIndex);
        console.log(elem);
        parent.appendChild(elem);
    }
}
return true;

现在它看起来好了一点,但仍然很奇怪。现在控制台输出为:

[li, li, li, li]
[li]
[li]
[li]
[li]

所以它有li元素,但不将它们视为HTMLNode…:o(与我使用elem !== null && elem !== undefined && elem.nodeType === 1时的结果相同)

您在while之前声明了maxIndex,在while中更改了数组,因此我建议您更改:

var curIndex = Math.floor(Math.random() * maxIndex);

到(这将确保curIndex始终小于tmpList.lenght)

var curIndex = Math.floor(Math.random() * tmpList.length);

然后拼接你的数组并验证你的元素:(为了更好地验证,你应该检查你的elem是否是html元素)

while(tmpList.length > 0) {
    var curIndex = Math.floor(Math.random() * tmpList.length);
    if (curIndex < tmpList.lenght){
        var elem = tmpList.splice(curIndex, 1);
        // array.splice returns array of removed from array elements, so you need work with first element in that array.
        if (elem[0] instanceof HTMLElement && elem[0].nodeType === 1){
            //Add to parent:
            parent.appendChild(elem[0]);
        }
    }
}  

您没有名为parent 的元素

好的,我发现了问题。诀窍是elem持有包含一个匹配元素的列表。解决方案是使用CCD_ 11。