如何使用javascript在ul标签中创建元素li img标签?

时间:2016-01-27 05:32:38

标签: javascript jquery html css

如何使用javascript在ul标签中创建元素li img标签?

我想创建

   4
    \
     2
    /
   6

内在

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

但不行,我该怎么做?

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

<ul id="placehere">

3 个答案:

答案 0 :(得分: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");

此处您使用相同的变量名称再次创建相同的elem元素,以便li丢失

将其更改为

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 :(得分:2)

  

首先将image元素附加到li元素,然后在li元素中附加ul元素。

在您的示例中,您在同一个变量(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

答案 2 :(得分: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);