参数 .replace() 两次 jQuery 插件不起作用

Parameters .replace() twice jQuery plugin doesn't works

我正在编写一个带参数的 jQuery 插件,但我无法设置两个参数。

jsfiddle

(function($) {
    $.fn.ototypo = function(options) {
        var defauts = {
            'aaa': true, // ON/OFF ponctuation 
            'bbbccc': true // ON/OFF parenthese
        };
        var parametres = $.extend(defauts, options);

        return this.each(function() {
            var aaa = $(this).html().replace(/a/g, "aaa");
            var bbbccc = $(this).html().replace(/b/g, "bbb").replace(/c/g, "ccc");

            if (parametres.aaa) {
                $(this).html(aaa)
            }

            if (parametres.bbbccc) {
                $(this).html(bbbccc)
            }
        });
    };
})(jQuery);

$('p').ototypo();

在这个例子中,我有两个函数,一个将 a 更改为 aaa,另一个将 b 更改为 bbb,将 c 更改为 ccc,我希望能够同时启用名为 aaabbbccc 的功能。如果我将 true 设置为函数,似乎只有最后一个有效。我需要禁用一个才能启用另一个,反之亦然。

最后一次调用 html 会覆盖之前对 html 的调用,因为你只替换原来的 HTML 你会丢失之前的替换等

(function($) {
    $.fn.ototypo = function(options) {

        var defauts = {
            'aaa': true, // ON/OFF ponctuation 
            'bbbccc': true // ON/OFF parenthese
        };

        var parametres = $.extend(defauts, options);

        return this.each(function() {
        
            var html = $(this).html();
            
            if (parametres.aaa) {
                html = html.replace(/a/g, "aaa");
            }
            
            if (parametres.bbbccc) {
                html = html.replace(/b/g, "bbb").replace(/c/g, "ccc");
            }
            
            $(this).html(html)
        });
    };
})(jQuery);

$('p').ototypo();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>abcdefghijklmnopqrstuvwxyz</p>

应该注意的是,您的方法将删除所有外部事件处理程序和 jQuery 存储的与元素相关的任何数据,并且它不适用于所有匹配传入的选择器等的嵌套元素。