问题
First off I'll start off by saying I am new to javascript so hopefully this isn't a complete face palm question. That being said, the following code should alert the value of the editor when the user clicks off of it.
<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>
Instead google chrome console reports:
"Uncaught TypeError: Cannot call method 'getData' of undefined "
Now when I change
var ckvalue = CKEDITOR.instances.editor.getData();
to
var ckvalue = CKEDITOR.instances.editor1.getData();
It works. This baffles me because I never declared a editor1 instance. I was hoping someone with a little more experience could explain to me why editor1 works when editor doesnt.
Here is a working example of what Im talking about: http://jsfiddle.net/s3aDC/6/
回答1:
editor is a JS variable that points to CKEDITOR.instances.editor1. See that editor === CKEDITOR.instances.editor1 // true.
Moreover, event callback is executed in editor context, so this points to editor:
editor.on('blur', function(event) {
var ckvalue = this.getData();
alert(ckvalue);
});
And you can define it when initializing the editor:
var editor = CKEDITOR.appendTo( 'textBox', {
on: {
blur: function( event ) {
console.log( this.getData() );
}
}
} );
And you should definitely avoid global variables in your code! ;)
回答2:
CKEditor gets editor name from:
- id or name attribute of textarea/editable element if editor isn't in "append to" mode: https://github.com/ckeditor/ckeditor-dev/blob/master/core/editor.js#L71
- function that generates unique editors names https://github.com/ckeditor/ckeditor-dev/blob/master/core/editor.js#L97
In your case editor is created by appendTo() method so CKEditor automatically generate name which is editor1, then editor2, etc. CKEDITOR.instances object contains all editor instances under their name, that's why there exists CKEDITOR.instances.editor1.
You assigned editor instance to global editor variable. But that's something completely different than editor name - you can have editor instance assigned to as many variables as you wish.
BTW. You should declare variables with var statement before using them.
来源:https://stackoverflow.com/questions/14062654/ckeditor-getdata-doesnt-seem-to-work-as-it-should