2016-12-02 60 views
0

我目前正在學習JavaScript和據我所知還沒有學會任何可以解釋如下:爲什麼我的變量似乎在更新?

<div id="parent"> 
    <div>One</div> 
    <div>Two</div> 
</div> 
<script> 
    function test(node) { 
     var divs = node.children; 
     console.log(divs); 
     var div = document.createElement("div"); 
     node.appendChild(div); 
     console.log(divs); 
    } 
    test(document.querySelector("#parent")); 
</script> 

我希望變量divs是包含node孩子div的存在,當一個對象代碼行已運行。它是什麼,但是當孩子被添加到父節點時它似乎更新。什麼解釋了這種行爲;我是否創建了對元素的引用,如果是的話,我該如何實現我想要的?

+0

見https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection,那就是'.children'給你。 – deceze

+0

謝謝你的失敗 – user6787998

回答

0

在JavaScript中,每個對象都通過引用而不是值傳遞。節點的.children屬性是一個對象(HTMLCollection對象是特定的)。這意味着'div'變量在運行時不會包含子元素,它會引用子元素屬性。當孩子改變並添加新節點時,訪問div變量將返回兒童的當前狀態,因此它也會包含新孩子。如果您只想將引用複製到初始孩子,則可以創建另一個變量。

function test(node) { 
    var children = node.children; 
    var divs = []; 

    // copy every child to the divs array 
    for (var i = 0; i < children.length; i++) { 
     divs.push(children[i]); 
    } 

    var div = document.createElement("div"); 
    node.appendChild(div); 

    // since divs is just an array copy of the initial children, 
    // when children change, the divs still only contains the initial nodes 
    console.log(divs); 

    // however, as we said before, children will still be a reference to 
    // current node's children, so 
    console.log(children); // outputs 3 divs 
} 
test(document.querySelector("#parent")); 
0

divs保持到所選擇的節點的children屬性的引用。因此,如果更改此children屬性,則divs的內容也會更改。

如果你想保持divs穩定,create a shallow copy of the array-like object children

function test(node) { 
    var divs = Array.prototype.slice.call(node.children); 
    console.log(divs); 

    var div = document.createElement("div"); 
    node.appendChild(div); 
    console.log(divs); 
} 
0

您可以創建一個新的數組

var divs = new Array(node.children.length); 
for(var i = 0; i < node.children.length; i++){ 
    divs[i] = node.children[i] 
} 
console.log(divs); 
var div = document.createElement("div"); 
node.appendChild(div); 
console.log(divs); 
0

您可以使用querySelectorAll,它返回一個靜態列表不住。欲瞭解更多詳情,你可以檢查這個鏈接。 https://www.w3.org/TR/selectors-api/#queryselectorall

<div id="parent"> 
    <div>One</div> 
    <div>Two</div> 
</div> 
<script> 
    function test(node) { 
     var divs = document.querySelectorAll('#'+node.id +' div'); 
     console.log(divs); 
     var div = document.createElement("div"); 
     node.appendChild(div); 
     console.log(divs); 
    } 
    test(document.querySelector("#parent",'#parent div')); 
</script> 
相關問題