从CKEditor中的光标位置获取文本的功能很奇怪

时间:2013-12-13 10:36:30

标签: text cursor ckeditor

我正在尝试从光标位置开始提取所有文本。这是我正在使用的代码:

originalText = editor.getData();
var startTag = "<span id=\x22Start\x22>&nbsp;</span>";
var stopTag = "<span id=\x22Stop\x22>&nbsp;</span>";
var startElement = CKEDITOR.dom.element.createFromHtml( startTag, editor.document );
editor.insertElement(startElement);
sText = editor.getData();
sText1 = sText + stopTag;
editor.setData(sText1);
// up to here, I've incapsulated the required text with span tags
// Using the replace function, I remove end tag of the Start span as well as removing    the start tag of the Stop span!
sText1 = editor.getData();
sText2 = sText1.replace("<span id=\"Start\">&nbsp;</span>", "<span id=\"Start\">");
sText2 = sText2.replace("<span id=\"Stop\">&nbsp;</span>", "</span>");
// I set the data (HTML) back to the editor
editor.setData(sText2);
//alert(sText2);
// I use the innerHTML to get the text
el = editor.document.$.getElementById("Start");
return el.innerHTML;

问题:    el.innerHTML工作正常但是如果取消注释alert()!我知道setData是异步的,通过在setData()上使用回调可以解决问题,但不幸的是它对我不起作用:(

1 个答案:

答案 0 :(得分:0)

尝试的快速修复确实是通过使用回调。使用回调你不能返回el.innerHTML,你必须调用外部函数。您没有显示调用此代码的代码,因此很难确定如何以您希望的方式重构此代码。下面是一个未经测试的虚拟版本,只是为您提供一个如何使用回调的示例。

function extractTextStartingFromCursorPosition(yourCallback) {
    originalText = editor.getData();
    var startTag = "<span id=\x22Start\x22>&nbsp;</span>";
    var stopTag = "<span id=\x22Stop\x22>&nbsp;</span>";
    var startElement = CKEDITOR.dom.element.createFromHtml( startTag, editor.document );
    editor.insertElement(startElement);
    sText = editor.getData();
    sText1 = sText + stopTag;

    editor.setData(sText1, function() {
        // up to here, I've incapsulated the required text with span tags
        // Using the replace function, I remove end tag of the Start span as well as removing    the start tag of the Stop span!
        sText1 = editor.getData();
        sText2 = sText1.replace("<span id=\"Start\">&nbsp;</span>", "<span id=\"Start\">");
        sText2 = sText2.replace("<span id=\"Stop\">&nbsp;</span>", "</span>");

        // I set the data (HTML) back to the editor
        editor.setData(sText2, function() {
            // I use the innerHTML to get the text
            el = editor.document.$.getElementById("Start");
            yourCallback(el.innerHTML);
        });
    });
}

所以,如果之前你使用过这样的函数:

var html = extractTextStartingFromCursorPosition();
doSomethingWithHtml(html);

现在你可以这样使用它:

extractTextStartingFromCursorPosition(function(html) {
    doSomethingWithHtml(html);
});

虽然我仍然觉得这个功能可能会以其他方式更好地完成,但我没有时间为相同的要求测试/重构新的解决方案。