使JQuery模板可重用 [英] Making JQuery templates reusable

查看:112
本文介绍了使JQuery模板可重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个将在整个项目范围内使用的jQuery模板.我希望将模板放在一个或多个单独的文件中,并在项目启动时使用 template 功能.

I want to create a jQuery template(s) that will be used project wide. I would prefer to put the templates in a separate file or files and compile them on project start up using the template function.

我不想在脚本标签的标记中包含模板.这可能吗,我该怎么办?

I don't want to have the templates in the markup, in script tags. Is this possible and how would I do it?

推荐答案

按照RoccoC5的建议,您可以定义一个小插件,该插件将获取您的远程模板,然后将其内容附加到脚本标签的头部:

As RoccoC5 suggested it, you can define a small plugin which will fetch your remote template and then append its content into a script tag to the head:

(function ($) {
    $.loadTmpl = function (url, name) {
        return $.get(url).success(function (content){
            $("head").append($('<script/>', {
                id: name,
                type: 'text/template'
            }).html(content));
        });
    };
}(jQuery));

并将其用于:

$.loadTmpl('hi.html', 'hi').done(function () {
    $('#hi').tmpl({name: 'Tom'}).appendTo('body');
});

或:

$.when(
    $.loadTmpl('foo.html', 'foo'),
    $.loadTmpl('bar.html', 'bar'),
    ...
).done(function () {
    // All your templates are now loaded
});

希望获得帮助.

这篇关于使JQuery模板可重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆