提问者:小点点

将字符串返回到另一个文件的jQuery代码


我有两个jQuery文件(templates.js&page.js)。 我需要的是访问我在templates.js文件中编写的模板(字符串或数组)到page.js。 我在谷歌上搜索了很多&; 无法解决我的问题。 我在templates.js之后加载page.js

这是我尝试过的。

templates.js

var templates = function ($) {

    var templateheader = function() { 
        console.log('templateheader: Till this console is working.');
        return '<h1>Put your Header here</h1>';
    }

    var templatefooter = function() { 
        console.log('templatefooter: Till this console is working.');
        var templateCode = [];
        templateCode.push(['title', 'My title'], ['content', 'My content']); 
        return templateCode;
    }
    return {
        templateheader : function () {
            templateheader();
        },
        templatefooter : function () {
            templatefooter();
        }
    }
}(jQuery);

page.js

var page = function ($) {
    var accessTemplate = function() { 
        mytemplate = templates.templateheader();
        mytemplateArr = templates.templatefooter();
    }
    return {
        accessTemplate : function () {
            accessTemplate();
        }
    }
}(jQuery);

console.log()在两种情况下都可以工作,但返回时,控制台中显示undefined


共1个答案

匿名用户

您的函数没有返回任何内容:

return {
    templateheader : function () {
        templateheader();
    },
    templatefooter : function () {
        templatefooter();
    }
}

我怀疑您打算返回以下值:

return {
    templateheader : function () {
        return templateheader();
    },
    templatefooter : function () {
        return templatefooter();
    }
}

不过老实说,你可以简化为:

return {
    templateheader : templateheader,
    templatefooter : templatefooter
}

或者甚至:

return { templateheader, templatefooter }