javascript - Internet Explorer 'InsertHTML' 兼容性问题

标签 javascript compatibility backwards-compatibility

我目前在使用 Internet Explorer 和我创建的 Javascript 时遇到问题。我一直试图找出不兼容问题的根源,但一直无法查明。

这在 Firefox 26 中运行良好,但在 Internet Explorer 11 中似乎并未实际生成表格。

function InsertTable()
{
column = document.getElementById("Columns").value
row = document.getElementById("Rows").value

cellwidth = 100 / column

table = '<table width="100%" border="2px">'

while(row > 0)
{
columncopy = column
table = table + '<tr>'

while(columncopy > 0)
{
table = table + '<td width="' + cellwidth + '%"></td>'
columncopy = columncopy - 1;
}

table = table + '</tr>'
row = row - 1;
}

table = table + '</table>'

document.getElementById("mainedit").focus();
document.execCommand('insertHTML', false, table);


}

更新:我设法将问题范围缩小到一行代码,它正在遍历整个过程,但实际上并没有正确放置它。

document.execCommand('insertHTML', false, table);

是问题的根源。

最佳答案

我找到了以下代码并按照以下方式集成了它。

html = table

IE()


function IE()
{

var sel, range;
if (window.getSelection) {
    // IE9 and non-IE
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();

        // Range.createContextualFragment() would be useful here but is
        // only relatively recently standardized and is not supported in
        // some browsers (IE9, for one)
        var el = document.createElement("mainedit");
        el.innerHTML = html;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ( (node = el.firstChild) ) {
            lastNode = frag.appendChild(node);
        }
        range.insertNode(frag);

        // Preserve the selection
        if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
} else if (document.selection && document.selection.type != "Control") {
    // IE < 9
    document.selection.createRange().pasteHTML(html);
}


}

关于javascript - Internet Explorer 'InsertHTML' 兼容性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21508332/

相关文章:

javascript - Jquery - 如果元素包含一个类,在元素之后添加 HTML

mysql - 查询失败,出现以下错误:: (Error #1366) Incorrect integer value: '' for column; how to set version compatibility

Spring 4.0.0 向后兼容

javascript - eval json 内存不足错误

javascript - jQuery 宽度不包括内部元素填充

javascript - 自定义 Handlebars 每个助手都有索引

python - 检查 Python 列表给出的兼容总订单

background - Mozilla 中的文本阴影和背景剪辑 css

ios - Swift 2 iOS 9 可用性全局变量

c - C 版本是否向后兼容?