本文主要說明CKEditor 取得編輯內容資料及初值設定編輯內容
一、存取資料主要了解 editor instance
CKEditor 4 Documentation
http://docs.ckeditor.com/#!/api/CKEDITOR.editor
圖1
二、setData
圖2
http://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-setData
程式基本寫法:
CKEDITOR.instances.editor1.setData( '<p>This is the editor data.</p>' );
三、getData
圖3
http://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-getData
程式基本寫法:
CKEDITOR.instances.editor1.getData()
四、程式
index_get_set.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery.min.1.11.1.js"></script>
<script src="ckeditor_4.5.7/ckeditor.js"></script>
<link rel="stylesheet" href="ckeditor_4.5.7/contents.css">
<script type="text/javascript">
$(document).ready(function() {
var editor = CKEDITOR.replace('content');
console.log("ready!");
CKEDITOR.instances.content.setData( '<p>This is the editor data.</p>' );
console.log(CKEDITOR.instances.content.getData());
});
</script>
</head>
<body>
<h2>Hello World!</h2>
<form id="detaform" method="post">
<textarea id="content" name="content"></textarea>
</form>
</body>
</html>
圖4
五、測試
圖5
六、 重點問題
本文中的instances 後接 content 是不是跟官網說明文件不一樣。
官網說明:
CKEDITOR.instances.editor1.setData()
CKEDITOR.instances.editor1.getData()
本文:
CKEDITOR.instances.content.setData()
CKEDITOR.instances.content.getData()
重點本文content 及 editor1 為什麼會不一樣,還可以執行呢?
因為本文textarea 名稱宣告為content。
var editor = CKEDITOR.replace('content');
....
<form id="detaform" method="post">
<textarea id="content" name="content"></textarea>
</form>
如果改為 editor1 需改幾個地方
var editor = CKEDITOR.replace('editor1');
....
<form id="detaform" method="post">
<textarea id="editor1" name="editor1"></textarea>
</form>
則取存資料:
CKEDITOR.instances.editor1.setData()
CKEDITOR.instances.editor1.getData()
所以要注意你的textarea 的id 、name的名稱喔!!
程式:
index_get_set_2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery.min.1.11.1.js"></script>
<script src="ckeditor_4.5.7/ckeditor.js"></script>
<link rel="stylesheet" href="ckeditor_4.5.7/contents.css">
<script type="text/javascript">
$(document).ready(function() {
var editor = CKEDITOR.replace('content');
console.log("ready!");
CKEDITOR.instances.content.setData( '<p>This is the editor data.</p>' );
console.log(CKEDITOR.instances.content.getData());
});
</script>
</head>
<body>
<h2>Hello World!</h2>
<form id="detaform" method="post">
<textarea id="content" name="content"></textarea>
</form>
</body>
</html>
測試:
圖6
下載本文測試專案 CKEditorTest5
下一篇:
CKFinder 下載
其它文章






沒有留言:
張貼留言