文件碎片和附加儿童

时间:2013-02-11 17:18:01

标签: javascript dom fragment children

我是文档片段概念的新手,我目前在确定如何将子项附加到片段时遇到一些麻烦。

这是我的HTML

<form>
  <ul id="tweets">
    <li><img src="tweetIcon.jpg"><span>This is my tweet</span></li>
  </ul>
</form>

以下是我的剧本:

var tweets = [
    "When teaching math, it shouldn't just be: 'Answer this question:'. It should also be:      'Question this answer:'",
    "Another reason to choose ",
    " Excellent! I love the new APIs that came with it, as well as the new tags and attributes.",
    "That's great. I am really grateful for your program and will definitely continue to encourage folks to enroll in courses!"
    ];

  function init() {
  var ul = document.getElementById("tweets");
  var fragment = document.createDocumentFragment();
  for (var i = 0; i < tweets.length; i++) {
    var tweet = tweets[i];
    var li = document.createElement("li");
    var span = document.createElement("span");
    span.innerHTML = tweet;
    var img = document.createElement("img");
    img.setAttribute("src", "tweetIcon.jpg");
    li.appendChild(span);
    ul.appendChild(li);
    fragment.appendChild(img);
    fragment.appendChild(li);
    }
    ul.appendChild(fragment);
  }

现在我只在列表顶部看到img和span元素一次。以下是正确显示为列表的推文的所有字符串。我需要为每条推文添加图片和span元素。注释掉的三行是我尝试将图像作为子元素添加到每个li元素的位置,但这些行实际上并没有做任何事情。有什么建议?谢谢!

1 个答案:

答案 0 :(得分:3)

document.createElement("img")移动到循环内,否则您将反复移动并更改相同的图像对象。