简体   繁体   中英

jQuery plugin returning undefined

I have a plugin to translate dom nodes. This it what it does:

$.fn.jqTranslate = function (pkg, options) {
    var self = this;
    Translate.initialize(pkg, options).done(function () {
        return self.each(Translate.translate);
    });
};
translate: function () {
    var elem = $(this),
        key = elem.data('translate');
    if (Translate.translatable) {
        if (Translate.translatedStrings[key]) {
            if (Translate.translatedStrings[key].length === undefined) {
                // The key have nested keys
                Translate.translateElement(elem, Translate.translatedStrings[key].text);
                delete Translate.translatedStrings[key].text;
                elem.attr(Translate.translatedStrings[key]);
            }
            else Translate.translateElement(elem, Translate.translatedStrings[key]);
        }
    }
    if (typeof Translate.options.onComplete === 'function') Translate.options.onComplete.apply(this, arguments);
    return elem;
}

If you see, it's returning self so the plugin could be theoretically chained like this:

$('p').jqTranslate('global').addClass('translated')

Should work but it says:

Uncaught TypeError: Cannot call method 'addClass' of undefined

What am I doing wrong?

You can check the full code in GitHub .

You are implicitly returning undefined from your plugin. When you have no return statement, a function returns undefined .

$.fn.jqTranslate = function (pkg, options) {
    var self = this;
    Translate.initialize(pkg, options).done(function () {
        return self.each(Translate.translate);
    });
    return this; //add return statement
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM