【问题标题】:Using innerHTML to add ordered list fails in IE在 IE 中使用 innerHTML 添加有序列表失败
【发布时间】:2010-06-07 14:55:37
【问题描述】:

我正在使用以下 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 中,它显示为好像 标签是
标签并忽略所有其他标签,如下所示:

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

我是否需要将有序列表动态添加到 DOM 才能正常工作?而不是仅仅使用 .innerHTML 在 div 中设置 html 代码?

TIA

【问题讨论】:

    标签: javascript innerhtml


    【解决方案1】:

    我是否需要将有序列表动态添加到 DOM 才能正常工作?而不是仅仅使用 .innerHTML 在 div 中设置 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(几乎为 -1 以坚持滥用 while 循环......)
    • 它在 IE7 中的行为仍然相同。 :( IE8 工作正常.. 有什么想法吗?我们必须支持 IE7,因为这是我们大多数用户使用的。
    • @Matt:我已经在 IE6 中测试过这个脚本(我现在没有 IE7)并且它正在工作,所以你的问题一定来自其他地方
    • 就是这样。谢谢你们的帮助。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 1970-01-01
      • 2022-01-08
      • 2019-05-01
      • 2012-07-19
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多