1

我正在尝试从 ckeditor 中获取特定区域的数据。为此,我使用以下代码

function get_body_html(){
    var email = CKEDITOR.instances['message'].getData();
    var before_body = header_to + to + to_subject + subject + subject_body;
    var s_index = email.indexOf(before_body)+before_body.length;
    var e_index = email.indexOf(body_footer);
    return email.substring(s_index,e_index);
}

出于某种原因,当我在页面加载时这样做时有效

CKEDITOR.instances.message.setData(header_to + to + to_subject+ 
subject + subject_body + body_text + body_footer);
get_body_html();

它工作正常,并给了我 body_text 中包含的相同字符串。

但是当我这样做时

body_text = get_body_html();
CKEDITOR.instances.message.setData(header_to + to + to_subject + subject + 
subject_body + body_text + body_footer);

在 onclick 函数中,它以某种方式获取错误的索引。有时它找不到字符串并返回 -1,有时它只是得到一个没有意义的奇怪索引。这些索引变化仅在我的代码被更改以以不同方式解决问题时发生。因此,如果是像 -5 和 2 这样的错误索引,那么在我进行代码更改之前,这些索引将继续是错误的索引。

4

2 回答 2

2

There are two facts that you should know about editor.setData.

  1. In some cases it is asynchronous (it depends on the type of editor). That's why it also accepts a callback. Therefore any code that is meant to be executed after setData() should be executed in that callback.
  2. It never is asynchronous before editor is ready. In this period (between editor initialization and instanceReady event) it works in a different mode - it just caches the set value and on getData() it returns exactly that value.

So, as I see on page load you call synchronously setData() and getData() - your function works because you get the value you're expecting to get.

But then, when you try to getData() when editor is already ready you get the HTML parsed, fixed, processed and perhaps differently formatted by CKEditor. I guess that your indexOf() checks are not enough to handle this. You have to rethink your function - e.g. regexp can help.

What also can help is removing htmlwriter plugin, which formats HTML in a way which may make it harder for you to work with it. E.g.:

config.removePlugins = 'htmlwriter';
于 2013-07-21T09:20:14.563 回答
0

我能够让它工作。所以 htmlwriter 是问题之一,因为它必须在 HTML 标记之间添加空格。我发现的另一个问题是它在一些样式属性中去掉了一些分号。总体而言,CKEditor 对源代码进行了很多格式化,这使得正确索引非常困难,但这几乎是一个反复试验的事情。我最终对可以采用正则表达式的字符串使用了搜索 JavaScript 方法,但我使用它的方式与使用 indexOf 的方式相同,所以我真的不知道这是否有所作为。

于 2013-07-22T23:08:12.210 回答