遍历CKEditor-4中的DOM节点 [英] Traversing DOM nodes in CKEditor-4
问题描述
我们在此CKEditor插件上有错误,而且通用解决方案是喜欢这个,只对DOM的终端文本节点应用通用字符串过滤器。 / p>
QUESTION :如何(需要代码示例)遍历选择节点( getEdit()
),例如 CKEDITOR.dom.range ?
第一步将从当前选择中获取范围。为此,只需调用:
var ranges = editor.getSelection()。getRanges
这给出一个范围数组,因为理论上(这个理论只由Firefox证明)选择可以包含许多范围。但在99%的现实世界的情况下,你可以只处理第一个而忽略其他。所以你有 range
。
现在,在这个范围内迭代每个节点的最简单的方法是使用 CKEDITOR.dom.walker
。使用它例如这样:
var walker = new CKEDITOR.dom.walker(range),
node;
while((node = walker.next())){
//记录范围内每个文本节点的日志值。
console.log(node.type == CKEDITOR.NODE_TEXT&&& node.getText());
}
但是,在范围边界处的文本节点存在问题。考虑以下范围:
< p> [foo< i> bar< / i> bo] m< / p&
这将记录: foo
, bar
和 bom
。是 - 整个 bom
,因为它是单个节点, walker不会修改DOM (文档中有错误)。
因此,如果它等于范围 startContainer
或 endContainer
如果是 - 只转换其范围内的那部分。
注意:我不知道walker的内部和我不知道你是否可以修改DOM,而迭代它。我建议先缓存节点,然后进行更改。
We have a bug at this CKEditor plugin, and a generic solution is like to this, applying a generic string-filter only to terminal text nodes of the DOM.
QUESTION: how (need code example) to traverse a selection node (editor.getSelection()
) by CKEditor-4 tools, like CKEDITOR.dom.range?
First step will be to get ranges from current selection. To do this just call:
var ranges = editor.getSelection().getRanges();
This gives you an array of ranges, because theoretically (and this theory is proved only by Firefox) one selection can contain many ranges. But in 99% of real world cases you can just handle the first one and ignore other. So you've got range
.
Now, the easiest way to iterate over each node in this range is to use CKEDITOR.dom.walker
. Use it for example this way:
var walker = new CKEDITOR.dom.walker( range ),
node;
while ( ( node = walker.next() ) ) {
// Log values of every text node in range.
console.log( node.type == CKEDITOR.NODE_TEXT && node.getText() );
}
However, there's a problem with text nodes at the range's boundaries. Consider following range:
<p>[foo<i>bar</i>bo]m</p>
This will log: foo
, bar
, and bom
. Yes - entire bom
, because it is a single node and walker does not modify DOM (there's a bug in documentation).
Therefore you should check every node you want to transform if it equals range's startContainer
or endContainer
and if yes - transform only that part of it which is inside range.
Note: I don't know walker's internals and I'm not sure whether you can modify DOM while iterating over it. I'd recommend first caching nodes and then making changes.
这篇关于遍历CKEditor-4中的DOM节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!