2016-01-27 101 views
0

如何使用javascript在ul標籤中創建元素li img標籤?如何使用javascript在ul標籤中創建元素li img標籤?

我想創建

<li id="123"> 
    <img src="https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif"/> 
</li> 

<ul id="placehere"> 

但是不行,我該怎麼做呢?

https://jsfiddle.net/btz69dyk/2/

<body> 
<script type="text/javascript"> 
window.onload=function(){ 

var elem = document.createElement("li"); 
elem.setAttribute("id", "123"); 

var elem = document.createElement("img"); 
elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif"); 
elem.setAttribute("height", ""); 
elem.setAttribute("width", ""); 
elem.setAttribute("alt", "Flower"); 
document.getElementById("placehere").appendChild(elem); 
} 
</script> 
<ul id="placehere"> 
</ul> 
</body> 

回答

2

問題是這4條線路

var elem = document.createElement("li"); 
elem.setAttribute("id", "123"); 

var elem = document.createElement("img"); 
elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif"); 

在這裏,你用相同的變量名稱,以便li丟失

改變它

再次創建相同 elem元素
var elem1 = document.createElement("li"); 
elem1.setAttribute("id", "123"); 

var elem = document.createElement("img"); 
elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif"); 
elem.setAttribute("height", ""); 
elem.setAttribute("width", ""); 
elem.setAttribute("alt", "Flower"); 
document.getElementById("placehere").appendChild(elem1); 
elem1.appendChild(elem); 
1

var listEle = document.createElement("li"); 
 
listEle.setAttribute("id", "123"); 
 

 
var elem = document.createElement("img"); 
 
elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif"); 
 
elem.setAttribute("height", ""); 
 
elem.setAttribute("width", ""); 
 
elem.setAttribute("alt", "Flower"); 
 
document.getElementById("placehere").appendChild(listEle).appendChild(elem);

2

追加image元件li元件在ul元件第一然後追加li元件。

在你的例子中,你是在同一個變量(elem)中創建元素,因此第二個元素將覆蓋早先創建的元素(變量將保存後面的元素)。附加image元素li元素DOM更新前,它會麻煩DOM結構只有一次..

試試這個:

window.onload = function() { 
 
    var li_elem = document.createElement("li"); 
 
    li_elem.setAttribute("id", "123"); 
 
    var img_elem = document.createElement("img"); 
 
    img_elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif"); 
 
    img_elem.setAttribute("height", ""); 
 
    img_elem.setAttribute("width", ""); 
 
    img_elem.setAttribute("alt", "Flower"); 
 
    li_elem.appendChild(img_elem); 
 
    document.getElementById("placehere").appendChild(li_elem); 
 
}
<ul id="placehere"> 
 
</ul>

Fiddle here