在IE中使用innerHTML添加有序列表失败

时间:2010-06-07 14:55:37

标签: javascript innerhtml

我正在使用以下Javascript代码来填充带有序列表的DIV:

// send script back in split list
var scriptList = script.split("\n");
var finalScript = "<ol>\n";
var count = 0;
while(scriptList.length >= count) {
    if((scriptList[count]=="") || (scriptList[count] == undefined))  {
        count ++;
        continue;
    }

    finalScript = finalScript + "<li>" + scriptList[count] + "</li>\n";
    count ++;
}
finalScript = finalScript + "</ol>";
scriptingDiv.innerHTML = finalScript;

在firefox中,如果我使用Firebug查看DOM,这会正确转换为以下内容并正确显示有序列表。

<ol>
<li>This is the first item in the list</li>
<li>This is the second item in the list</li>
</ol>

在IE中,它显示为&lt; / li&gt;标签是&lt; br /&gt;标记并忽略所有其他标记,如下所示:

  

这是列表中的第一项   这是列表中的第二项

我是否需要动态地将有序列表添加到DOM才能使用?而不是仅使用.innerHTML在

中设置html代码?

TIA

2 个答案:

答案 0 :(得分:2)

  

我是否需要动态地将有序列表添加到DOM才能使用?而不是仅使用.innerHTML在

中设置html代码?

var scriptList = script.split("\n");
var count = 0;
var ol = document.createElement("ol");

    for(var index=0; index<scriptList.length; index++) {
        if(scriptList[index]!="")  {
            var li = document.createElement("li");
            li.innerHTML=scriptList[index];
            ol.appendChild(li);
        }
    }

scriptingDiv.appendChild(ol);

答案 1 :(得分:0)

为什么不使用dom方法呢? IE:

myOL = document.createElement("ol");
myLI = document.createElement("li");
myTxt = document.createTextNode("My Text!");
myLI.appendChild(myTxt);
myOL.appendChild(myLI);