Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

javascript - IE innerHTML error

This is a little different than the questions that have already been asked on this topic. I used that advice to turn a function like this:

function foo() {

    document.getElementById('doc1').innerHTML = '<td>new data</td>';

}

into this:

function foo() {

    newdiv = document.createElement('div');
    newdiv.innerHTML = '<td>new data</td>';

    current_doc = document.getElementById('doc1');
    current_doc.appendChild(newdiv);

}

But this still doesn't work. An "unknown runtime error" occurs on the line containing innerHTML in both cases.

I thought creating the newdiv element and using innerHTML on that would solve the problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not possible to create td or tr separately in Internet Explorer. This same problem has existed in other browsers for quite some time too, however latest versions of those do not suffer from that issue any more.

You have 2 options to:

  1. Use table specific APIs to add cells/rows. See for example MSDN for insertCell and more
  2. Create a utility function, that would help you creating DOM nodes out of strings. In case of a table you would need to wrap up your HTML so that the resulting HTML is always a table and then get required element by tag name.

For example like this:

var oHTMLFactory = document.createElement("span");
function createDOMElementFromHTML(sHtml) {
    switch (sHtml.match(/^<(w+)/)) {
        case "td":
        case "th":
            sHtml   = '<tr>' + sHtml + '</tr>';
            // no break intentionally left here
        case "tr":
            sHtml   = '<tbody>' + sHtml + '</tbody>';
            // no break intentionally left here
        case "tbody":
        case "tfoot":
        case "thead":
            sHtml   = '<table>' + sHtml + '</table>';
            break;
        case "option":
            sHtml   = '<select>' + sHtml + '</select>';
    }
    oHTMLFactory.innerHTML = sHtml;

    return oAML_oHTMLFactory.getElementsByTagName(cRegExp.$1)[0] || null;
}

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...