zoukankan      html  css  js  c++  java
  • 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>

    测试截图如下:

    点击第二个按钮之后:

  • 相关阅读:
    Codeforces 1249 F. Maximum Weight Subset
    Codeforces 1249 E. By Elevator or Stairs?
    Codeforces 1249 D2. Too Many Segments (hard version)
    使用subline作为Stata外部编辑器,并实现代码高亮
    Getting a handle on
    Economics degrees
    The threat to world
    他山之石,calling by share——python中既不是传址也不是传值
    Python的几个爬虫代码整理(网易云、微信、淘宝、今日头条)
    一梦江湖费六年——QQ群聊天分析
  • 原文地址:https://www.cnblogs.com/zhuxinghan/p/6058602.html
Copyright © 2011-2022 走看看