獲取 CKEditor 的 HTML 內容

使用以下內容建立檔案 ckeditor-content.html

<!DOCTYPE html>
<html>
<head>
    <title>CKEditor Get Content Demo!</title>
</head>
<body>
    <script src="//cdn.ckeditor.com/4.6.1/basic/ckeditor.js"></script>
    <div id="editor1" contenteditable="true">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In est ipsum, elementum id ipsum vel, aliquam lobortis ligula. Nam vel purus eget nulla bibendum interdum at non orci. Nulla facilisi. Vivamus aliquet sapien risus. Mauris molestie efficitur pharetra. Aliquam erat volutpat. Fusce ac leo pretium, ornare libero et, tincidunt erat. Nunc tempus tortor eget ex ultricies, a cursus nibh fringilla.<br /><br />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In est ipsum, elementum id ipsum vel, aliquam lobortis ligula. Nam vel purus eget nulla bibendum interdum at non orci. Nulla facilisi. Vivamus aliquet sapien risus. Mauris molestie efficitur pharetra. Aliquam erat volutpat. Fusce ac leo pretium, ornare libero et, tincidunt erat. Nunc tempus tortor eget ex ultricies, a cursus nibh fringilla.<br /><br />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In est ipsum, elementum id ipsum vel, aliquam lobortis ligula. Nam vel purus eget nulla bibendum interdum at non orci. Nulla facilisi. Vivamus aliquet sapien risus. Mauris molestie efficitur pharetra. Aliquam erat volutpat. Fusce ac leo pretium, ornare libero et, tincidunt erat. Nunc tempus tortor eget ex ultricies, a cursus nibh fringilla.<br /><br />
    </div>
    <button id="btn1">Click to get the content</button>
    <script>
        document.getElementById('btn1').addEventListener('click', function() {
            content = CKEDITOR.instances.editor1.getData()
            console.log(content);
        }, false);
    </script>
</body>
</html>

JSFiddle 上的現場演示

程式碼說明

  1. 從 CKEditor CDN 載入 CKEditor 庫:

        <script src="https://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.6.1/ckeditor.js"></script>
    
  2. 使用編輯器中包含的所有內容建立一個新的 DIV 元素

    <div id="editor1" contenteditable="true">
    ALL CONTENT HERE
     </div>
    
  3. click 監聽器新增到我們的按鈕,一旦點選 - 獲取 ckeditor 的 HTML 內容。

     <script>
         document.getElementById('btn1').addEventListener('click', function() {
             content = CKEDITOR.instances.editor1.getData()
             console.log(content);
         }, false);
     </script>
    
  1. CKEDITOR.instances.editor1 中編輯器 editor1 的名稱是我們使用的元素的 id 屬性的值(<div id="editor1" ... >
  2. 注意 console.log 的用法 - 編輯器的 HTML 內容將在控制檯中提供(你可以通過單擊 F12 鍵開啟控制檯 )

有關更多資訊,請參閱內聯文件頁面。