【问题标题】:jquery contents() returns text node for each character in IEjquery contents() 返回 IE 中每个字符的文本节点
【发布时间】:2010-12-13 16:01:11
【问题描述】:

我正在实现一个解析器,它在 contenteditable div 的顶层查找匹配模式的文本节点。我当前的代码:

//$this is the jQuery object of the contenteditable div
$this.keydown(function(event){
    //space bar or enter key
    if(event.keyCode == 32 || event.keyCode == 13){
      // see how many nodes there are in the div
      alert($this.contents().length); 
      $this.contents().each(function(){
          //check if it is a text node
          if(this.nodeType == 3){ 
              //echo if it is a text node
              alert(this.data); 
           }
      });
});

使用“Check it out”内容,firefox 和 chrome 会输出如下内容:

“1”(第一个警报)
“检查一下”(第二个警报)

而 IE8 将输出以下内容:
12(第一次警报)
接下来是 12 个警报,每个字符一个。

Anyhoo,我想做的是将所有字符放入 IE 中的单个文本节点中。有什么想法吗?

【问题讨论】:

    标签: javascript jquery internet-explorer contenteditable


    【解决方案1】:

    为此有一个 DOM 方法:normalize()(另请参阅MDC)。您需要在要规范化的文本节点的祖先(例如它们的父节点)上调用它。 normalize() 适用于调用它的节点的整个子树,因此您可以在 each() 循环之外调用它一次。

    $this[0].normalize();
    

    但是,这种方法在某些情况下会在 IE 6 和更高版本的 IE 中使整个浏览器崩溃。您可能需要自己编写。这是我的实现:

    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;
        }
    }
    

    【讨论】:

    • 不知道谁回答了我的问题...感谢您的rangy library Tim!
    猜你喜欢
    • 2020-06-25
    • 2014-04-11
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-08-12
    相关资源
    最近更新 更多