Bruno Landowski Bruno Landowski - 2 months ago 7
jQuery Question

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

I'm writing a jQuery Plugin with parameters but I don't manage to set two parameters.

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();


In this example I've two functions, one changing
a
to
aaa
and the other changing
b
to
bbb
and
c
to
ccc
, I would like to be able to enable both fonction called
aaa
and
bbbccc
. If I set
true
to the fonctions, only the last seems to works. I need to disable one to enable the other and vice-versa.

Answer

The last call to html overwrites the previous call to html and as you only replace on the original HTML you lose the prevoius replacement etc.

(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>

It should be noted that your approach would remove all external event handlers and any data stored by jQuery related to the elements, and it won't work with nested elements all matching the passed in selector etc.