我对文档片段的概念很陌生,目前在弄清楚如何将子项附加到片段中时遇到一些困难。
这是我的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 元素的地方,但这些行实际上并没有做任何事情。有什么建议么?谢谢!
最佳答案
将 document.createElement("img")
移动到循环内,否则您将重复移动和更改同一图像对象。
关于javascript - 文档片段和附加子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14817294/