2013-02-11 77 views
0

我是新來的文件片段的概念,我目前有一些麻煩,搞清楚如何追加兒童片段。文件片段和附加的孩子

這是我的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元素只有一次在列表的頂部。以下是正確顯示爲列表的tweets的所有字符串。我需要將圖像和span元素添加到每條推文。註釋掉的三行是我試圖將圖像添加到每個li元素作爲孩子的地方,但這些行並沒有真正做任何事情。有什麼建議麼?謝謝!

回答

3

document.createElement("img")移到循環內部,否則您會反覆移動並更改同一圖像對象。

+0

謝謝我編輯了上面的代碼。儘管如此,我仍然遇到了span元素的問題。現在它包含來自變量tweet的文本,但它顯示在每個twitter圖標圖像下面,我想要它做的就是在它旁邊顯示,就像html中的span元素一樣。 – user1876829 2013-02-11 19:48:40

+0

將圖像追加到li,然後將span擴展到li,然後將li添加到ul。電腦不會猜測你的意思。 – 2013-02-11 19:49:50

+0

非常感謝! – user1876829 2013-02-11 19:55:09