wangEditor是一款優秀的Web富文本編輯器。這篇隨筆中講述的wangEditor版本是2.1.22,由於它依賴於jQuery(作者打算在第三版中取消對jQuery的依賴),那么如果能使用$("#editor").wangeditor()的方式創建和獲取編輯器,就再好不過了。為了達到這個目的,需要為jQuery定制一款插件,代碼如下:
(function ($) { // 用於存儲所有編輯器實例的對象。由於wangEditor不支持從原始元素或其id獲取已經創建好的編輯器實例,使用這個對象可以方便以后獲取編輯器實例 var editors = {}; // 注冊jQuery插件 $.fn.wangeditor = function () { // 如果通過jQuery獲取了多個元素,可以創建多個編輯器 for (var i = 0; i < this.length; i++) { var id = this[i].id; // 如果之前沒有創建過對應的編輯器,則創建編輯器並放入編輯器實例存儲對象 if (editors[id] == undefined) { editors[id] = new wangEditor(id); editors[id].create(); } } // 只返回第一個元素對應的編輯器實例。因此,如果要獲取編輯器,使用的選擇器應該只匹配一個元素,多余的元素將忽略 return editors[this[0].id]; }; })($);
下面寫一個頁面測試這款插件。在這個頁面中包含了多個編輯器,可以驗證這款插件支持多個編輯器的創建和單一編輯器實例的獲取:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8" /> <link href="Content/wangEditor/css/wangEditor.css" rel="stylesheet" /> </head> <body> <div id="editor1" class="editor"> <h3>wangEditor的jQuery插件化1</h3> </div> <div id="editor2" class="editor"> <h3>wangEditor的jQuery插件化2</h3> </div> <button type="button" data-editor="1">顯示內容1</button> <button type="button" data-editor="2">顯示內容2</button> <script src="Scripts/jquery-3.1.1.js"></script> <script src="Scripts/wangEditor.js"></script> <!-- 引入剛才編寫的插件 --> <script src="Scripts/jquery-wangeditor.js"></script> <script> // 一次調用,創建多個編輯器 $(".editor").wangeditor(); $("button[data-editor]").click(function () { // 用同樣的方法獲取單一編輯器實例,然后顯示其文本內容 alert($("#editor" + $(this).data("editor")).wangeditor().$txt.text()); }); </script> </body> </html>
測試截圖如下:
點擊第二個按鈕之后: