innerHTML causing ul to self-close

一曲冷凌霜 提交于 2019-12-10 21:15:45

问题


I'm trying to display a Twitter feed by pulling from a cached text file and looping through the tweets. Works fine until I try to turn these tweets into a list. The li elements append to the innerHTML properly, but the opening ul self-closes, and the ending ul disappears.

function twitterStatusCallback(obj) {
   if(obj && obj.length){
       document.getElementById('twitter_status').innerHTML += "<ul>";
       var len = obj.length;

      for(var i = 0; i < len; i++){
    //Only get tweets less than 7 days old.
    if ((relativeTimeNumeric(obj[i].created_at)) < (8*24*60*60)) { 

    var tweet = obj[i];

        document.getElementById('twitter_status').innerHTML += "<li>" + linkify(tweet.text);
        document.getElementById('twitter_status').innerHTML += relativeTime(tweet.created_at) +"</li>";

   }
   }
  document.getElementById('twitter_status').innerHTML += "</ul>"; 
}
 }

回答1:


How about building a string and then assigning it to innerHTML when it's completely built (so you never inject broken html). Firing broken html into the browser bit by bit is bound to cause problems, because the browser cannot store a broken dom tree.




回答2:


This is probably a browser specific issue. I would recommend constructing a string for the innerHTML first, and assigning it at the end of your function.

ie:

var temp = "<ul>";
temp += "<li">;

etc...

document.getElement.innerHTML = temp;



回答3:


More clean

​var ul=document.createElement('ul');
for(i=0;i<len;i++)
{
    var li=document.createElement('li');
    li.innerHTML=linkify(tweet.text)+" "+relativeTime(tweet.created_at);
    ul.appendChild(li);
}

document.getElementById('twitter_status').appendChild(ul);

An example here.



来源:https://stackoverflow.com/questions/10115711/innerhtml-causing-ul-to-self-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!