我是文档片段概念的新手,目前在弄清楚如何将子项附加到片段时遇到了一些麻烦。
这是我的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 元素作为孩子的地方,但这些行并没有真正做任何事情。有什么建议么?谢谢!