简体   繁体   English

surroundContents()更改`live`?

[英]surroundContents() make changes `live`?

Links to live examples @ jsfiddle & jsbin . 实时示例@ jsfiddlejsbin的链接

So this function: 所以这个功能:

function symbolize(e){
    var elements = e.childNodes; // text nodes are necessary!
    console.log(elements);
    for(var i=0; i < elements.length; i++){
        t = elements[i];
        var range = document.createRange(), offset = 0, length = t.nodeValue.length;
        while(offset < length){
            range.setStart(t, offset); range.setEnd(t, offset + 1);
            range.surroundContents(document.createElement('symbol'));
            offset++;
        }
    }
}

..should iterate over every letter and wrap it in a <symbol/> element. ..应该迭代每个字母并将其包装在<symbol/>元素中。 But it doesn't seem to be working. 但它似乎没有奏效。

So I added the console.log(); 所以我添加了console.log(); right after the *.childNodes have been fetched, but as you'll see in the example site above, the log contains 2 unexpected elements in front(!) of the array. 在获取*.childNodes之后,正如您在上面的示例站点中看到的那样,日志在数组的前面(!)中包含2个意外元素。 And yeah, because of this, I have a feeling that surroundContents(); 是的,因为这个,我有一种感觉,即surroundContents(); make the changes live(!). 实时更改(!)。 couldn't find any reference on this though 虽然没有找到任何参考

One of the elements is an empty Text node, the other is my <symbol/> . 其中一个元素是空Text节点,另一个是我的<symbol/> But yeah, this is totally unexpected result and messes up the rest of the function. 但是,这是完全出乎意料的结果,并且会影响其余的功能。

What could be wrong with it? 它可能有什么问题?

Thanks in advance! 提前致谢!

Update 更新

Oh, looks like the elements are added on Chrome, Firefox doesn't add the elements, but still halts the function. 哦,看起来Chrome上添加了元素,Firefox没有添加元素,但仍然停止了功能。

Element.childNodes is indeed a live list , it could not be otherwise (that would mean an incorrect list of nodes). Element.childNodes确实是一个实时列表,它不可能是其他(这意味着不正确的节点列表)。 The easiest solution is to freeze (make a copy of) it before you mess with it (by surrounding existing ranges). 最简单的解决方案是在混乱之前冻结(复制)它(通过包围现有范围)。

var elements = Array.prototype.slice.call(e.childNodes, 0);

https://developer.mozilla.org/en/childNodes it's of type NodeList https://developer.mozilla.org/En/DOM/NodeList those are live lists https://developer.mozilla.org/en/childNodes它的类型为NodeList https://developer.mozilla.org/En/DOM/NodeList这些是实时列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM