簡體   English   中英

JS DOM追加子項不起作用

[英]JS DOM append child does not work

我正在嘗試實現一個簡單的函數,該函數獲取一些元素列表(在這種情況下,我傳遞一些<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元素在前面定義了幾行,實際情況並非如此。

UPDATE

我根據一個答案進行了一些更改,因此代碼如下:

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

你宣布maxIndex之前whilewhile你改變你的陣列,所以我建議你更改:

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持有包含一個匹配元素的列表。 解決方案是使用elem[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM