2016-12-22 103 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>