【问题标题】:Parameters .replace() twice jQuery plugin doesn't works参数 .replace() 两次 jQuery 插件不起作用
【发布时间】:2016-10-04 15:18:06
【问题描述】:

我正在编写一个带有参数的 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 更改为bbbc 更改为ccc,我希望能够同时启用这两个函数函数名为 aaabbbccc。如果我将true 设置为函数,则似乎只有最后一个有效。我需要禁用一个来启用另一个,反之亦然。

【问题讨论】:

    标签: javascript jquery replace jquery-plugins


    【解决方案1】:

    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 存储的与元素相关的任何数据,并且它不适用于所有匹配传入选择器等的嵌套元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-13
      • 2016-03-23
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      相关资源
      最近更新 更多