【问题标题】:IE9: childNodes not updated after splitText?IE9:splitText 后子节点未更新?
【发布时间】:2011-11-14 17:52:36
【问题描述】:

在 Internet Explorer 9 上,在文本节点上调用 splitText 不会更新其父节点的 childNodes。正如https://developer.mozilla.org/En/DOM/Text.splitText 所预期的那样,在 Chrome 和 Firefox 上它确实如此。

但是在文本节点父 (?) 上调用 console.dir 时,IE9 的行为正常

例子:

<!DOCTYPE html>
<html lang="en">

<meta charset="utf-8">

<script type="text/javascript" charset="utf-8">

window.onload = function() {

  var e = document.querySelector('#test p');

  var f = e.childNodes[0].splitText(10);

  console.log(e.childNodes.length)

  // console.dir(e)

  console.log(e.childNodes.length)

}

</script>

<div id="test">
  <p>Senectus et netus et malesuada fames ac turpis egestas.</p>
</div>

</html>

IE9 输出:

LOG: 1
LOG: 1

Chrome 和 Firefox 都正确输出:

2
2

取消注释 console.dir(e) 时,现在 IE9 输出:

LOG: 1
LOG: [object HTMLParagraphElement] {}
LOG: 2

这是一个错误吗?如果是这样,除了console.dir之外,是否有任何解决方法可以“刷新”并反映childNodes的实际状态?

更新目前似乎可行的是添加/删除节点,例如:

var t = document.createTextNode("");
e.appendChild(t);
e.removeChild(t);

【问题讨论】:

    标签: dom internet-explorer-9


    【解决方案1】:

    您可以使用解决方法代替splitText()

    function insertAfter(node, precedingNode) {
        var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;
        if (nextNode) {
            parent.insertBefore(node, nextNode);
        } else {
            parent.appendChild(node);
        }
        return node;
    }
    
    // Note that we cannot use splitText() because it is bugridden in IE 9.
    function splitDataNode(node, index) {
        var newNode = node.cloneNode(false);
        newNode.deleteData(0, index);
        node.deleteData(index, node.length - index);
        insertAfter(newNode, node);
        return newNode;
    }
    

    【讨论】:

    • 谢谢。我已经在使用我的解决方法,它似乎工作正常,没有明显的性能损失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多