Node.normalize()在IE6中崩溃

Chr*_*ard 5 javascript dom internet-explorer-6

我正在javascript中对TextNodes进行一些操作,我(不幸的是)需要支持IE6.Node.normalize()崩溃了,我需要解决这个问题.我的第一个倾向是使用其他DOM方法重新实现它.我该如何实现?

Tim*_*own 7

以下版本比此处发布的版本更短,更高效.改进是:

  • 没有重复的电话node.childNodesnode.childNodes.length
  • 没有创建额外的文本节点; 相反,对于每个合并,保留第一个现有文本节点并使用其appendData()方法

代码:

function normalize(node) {
    var child = node.firstChild, nextChild;
    while (child) {
        if (child.nodeType == 3) {
            while ((nextChild = child.nextSibling) && nextChild.nodeType == 3) {
                child.appendData(nextChild.data);
                node.removeChild(nextChild);
            }
        } else {
            normalize(child);
        }
        child = child.nextSibling;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*sch 5

上面的解决方案运行非常慢,并为我崩溃Firefox.所以我对它进行了优化,现在它工作得很好(主要问题是重复引用HTML集合对象node.childNodes).

感谢伟大的起点,但我认为这值得发布:


function myNormalize(node) {
    for (var i=0, children = node.childNodes, nodeCount = children.length; i<nodeCount; i++) {
        var child = children[i];
        if (child.nodeType == 1) {
            myNormalize(child);
            continue;
        }
        if (child.nodeType != 3) { continue; }
        var next = child.nextSibling;
        if (next == null || next.nodeType != 3) { continue; }
        var combined_text = child.nodeValue + next.nodeValue;
        new_node = node.ownerDocument.createTextNode(combined_text);
        node.insertBefore(new_node, child);
        node.removeChild(child);
        node.removeChild(next);
        i--;
        nodeCount--;
    }
}
Run Code Online (Sandbox Code Playgroud)