ckeditor getData()似乎没有按预期工作

Jes*_*sse 4 javascript ckeditor

首先,我将首先说我是javascript的新手,所以希望这不是一个完整的问题.话虽这么说,下面的代码应该在用户点击它时提醒编辑器的值.

<script type='text/javascript'>
function openEditor(){
html = "Hello World";
config = {
startupFocus : true
};
editor = CKEDITOR.appendTo( 'textBox', config, html );


 if (editor) {
    editor.on('blur', function(event) {
        var ckvalue = CKEDITOR.instances.editor.getData();
        alert(ckvalue);
    });
 }
}
</script>
<html>
<a href='#' onclick='openEditor()'>Open Editor</a><br />
<div id='textBox'></div>
</html>
Run Code Online (Sandbox Code Playgroud)

而是谷歌Chrome控制台报告:

"Uncaught TypeError: Cannot call method 'getData' of undefined "

现在当我改变

var ckvalue = CKEDITOR.instances.editor.getData();
Run Code Online (Sandbox Code Playgroud)

var ckvalue = CKEDITOR.instances.editor1.getData();
Run Code Online (Sandbox Code Playgroud)

有用.这让我感到困惑,因为我从未声明过editor1实例.我希望有更多经验的人可以向我解释为什么当编辑器没有时,editor1会起作用.

这是我正在谈论的一个工作示例:http://jsfiddle.net/s3aDC/6/

ole*_*leq 5

editor是一个指向的JS变量CKEDITOR.instances.editor1.看到了editor === CKEDITOR.instances.editor1 // true.

此外,事件回调在editor上下文中执行,因此this指向editor:

editor.on('blur', function(event) {
    var ckvalue = this.getData();
    alert(ckvalue);
});
Run Code Online (Sandbox Code Playgroud)

您可以在初始化编辑器时定义它:

var editor = CKEDITOR.appendTo( 'textBox', {
    on: {
        blur: function( event ) {
            console.log( this.getData() );
        }
    }
} );
Run Code Online (Sandbox Code Playgroud)

你绝对应该避免代码中的全局变量!;)