2016-12-22 33 views
0

我有以下代碼在js單擊函數中爲兩個div(myList,myList1)編寫列表元素。DOM appendChild不適用於兩個變量

我追加立兒兩個,但只有第二個div得到更新,但第一個div沒有更新,

\t function myFunction() { 
 
\t var node = document.createElement("LI"); 
 
\t var textnode = document.createTextNode("Water"); 
 
\t node.appendChild(textnode); 
 
\t document.getElementById("myList").appendChild(node); 
 
\t document.getElementById("myList1").appendChild(node); 
 
\t }
<!DOCTYPE html> 
 
<html> 
 

 
<body> 
 

 
    <ul id="myList"> 
 
    <li>Coffee</li> 
 
    <li>Tea</li> 
 
    </ul> 
 

 
    <ul id="myList1"> 
 
    <li>Coffee</li> 
 
    <li>Tea</li> 
 
    </ul> 
 

 
    <button onclick="myFunction()">Try it</button> 
 

 
</body> 
 

 
</html>

它產生下面的輸出,

myList: 
    ------- 
Coffee 
Tea 

myList1: 
    ------- 
Coffee 
Tea 
Water 

我在找的實際產量如下,

myList: 
    ------- 
Coffee 
Tea 
Water 

myList1: 
    ------- 
Coffee 
Tea 
Water 

我錯過了這裏的東西,有人可以建議它是什麼。

在此先感謝。

+1

*如果節點是DOM現有節點,它將被刪除舊的並放到新的位置* - js doc –

+0

只是給你清晰的想法看到小提琴實際上發生了什麼https://jsfiddle.net/5zmsxem0/2/ –

回答

4

這是因爲appendchild將節點從第一個ul移動到第二個ul。

此行

document.getElementById("myList").appendChild(node); 

節點添加到UL myList中但很下一行

document.getElementById("myList1").appendChild(node); 

myList中節點移動到myList1

你可以克隆你的節點以獲得所需的結果LT。

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<ul id="myList"> 
 
    <li>Coffee</li> 
 
    <li>Tea</li> 
 
</ul> 
 

 
<ul id="myList1"> 
 
    <li>Coffee</li> 
 
    <li>Tea</li> 
 
</ul> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<script> 
 
function myFunction() { 
 
    var node = document.createElement("LI"); 
 
    var textnode = document.createTextNode("Water"); 
 
    node.appendChild(textnode); 
 
    var newNode = node.cloneNode(true); 
 
    document.getElementById("myList").appendChild(node); 
 
    document.getElementById("myList1").appendChild(newNode); 
 
} 
 
</script> 
 
</body> 
 
</html>

0

你不能追加到多個elems的一個節點。你需要克隆它:

var elem=document.createElement("Li"); 
//add text 
elem2=elm.cloneNode(true); 
//append to dom 
1

至於你的問題有一個jQuery的標籤,你應該試試這個:

function myFunction() { 
 
    node = $('<li/>').html("water") 
 
    $('ul').append(node) 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<ul id="myList"> 
 
    <li>Coffee</li> 
 
    <li>Tea</li> 
 
</ul> 
 

 
<ul id="myList1"> 
 
    <li>Coffee</li> 
 
    <li>Tea</li> 
 
</ul> 
 

 
<button onclick="myFunction()">Try it</button>