[英]DOM Manipulation
Newbie question - Is this code eloquent enough to create four list items? 新手问题-此代码雄辩地说足以创建四个列表项吗? or Should I be using documentFragment instead?
还是应该改用documentFragment? The code seems to work fine - JsFiddle .
该代码似乎可以正常工作-JsFiddle 。
Created list and li variables 创建列表和li变量
var list = document.getElementById("myList");
var li = null;
Created x number of list elements and companion text nodes 创建了x个列表元素和伴随文本节点
for(var i=1; i<=4; i++){
var li = document.createElement("li");
li.appendChild(document.createTextNode("Number " + i));
Add li to list 将li添加到列表
list.appendChild(li);
} }
Based entirely on the JSFiddle demo you've provided: No. What you currently have is semantically incorrect. 完全基于您提供的JSFiddle演示:不。您当前拥有的在语义上是不正确的。 You're currently appending your
li
to the body
, not the ul
element: 您当前正在将
li
附加到body
, 而不是 ul
元素上:
<ul></ul>
<li>Number 1</li>
Change: 更改:
document.body.appendChild(li);
To: 至:
list.appendChild(li);
As for the code you've provided in the question, you also need to change it so that your li
elements get appended to your ul
element. 至于您在问题中提供的代码,还需要更改它,以便将
li
元素附加到ul
元素上。 You also need to change your class
into an ID
, as getElementById("myList")
pulls an element with an ID of "myList", whereas your current ul
has no such ID. 您还需要将您的
class
更改为ID
,因为getElementById("myList")
提取ID为“ myList”的元素,而您当前的ul
没有此类ID。
Actually there is an error, because you're adding the li
s to the body
instead of the ul
also the markup is not well created, change 实际上存在错误,因为您是将
li
而不是ul
添加到body
中,所以标记也没有很好地创建,请更改
<ul class="myList"></ul>
with 与
<ul id="myList"></ul>
To use an id
and then: 要使用
id
,然后执行以下操作:
var list = document.getElementById("myList");
var li = null;
for(var i=1; i<=4; i++){
var li = document.createElement("li");
li.appendChild(document.createTextNode("Number " + i));
//document.body.appendChild(li); **error here**
list.appendChild(li); //fix
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.