wangEditor的jQuery插件化

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>

测试截图如下:

点击第二个按钮之后:

posted @ 2016-11-13 14:00  zhu'sDevlog  阅读(2628)  评论(3编辑  收藏  举报