HTML模板内的JavaScript文件.我做错了什么?

HTML templates inside JavaScript file... What am I doing wrong?

本文关键字:错了 什么 文件 JavaScript HTML      更新时间:2023-09-26

我想要实现的是存储所有需要在单独的js文件中生成的HTML模板(而不是在页面中呈现)。

buildHtml函数当前的设置工作良好。我被困的地方是如果…模板对象中还有一个变量input3它的标记是<div>(exact markup from commonInput)</div>

我试着用它作为input 3 : '<div>' + this.commonInput + '</div>',但事实证明你不能从内部使用this引用对象属性(在这里解释)。

我可以用完整的html创建'input3',但对于大的html块,这种方法不是很有用。

寻找

  1. 解决方案
  2. 解释这种方法是否是个坏主意
  3. 更好的选择

    $j(document).ready(function() {
    var namespace = window.namespace || {};
    namespace.feature = namespace.appName || {};
    namespace.feature.templates = {
    input1  :   '<div>'+
                    '<p class="abc">Hey {username}</p>'+
                '</div>',
    input2  :   '<div>'+
                    '<div class="description">{description}</div>'+
                '</div>',
    commonInput :   '<div class="common">Common code</div>'
    };
    namespace.feature.module = function() {
    var container  = $j('#container'),
        t = namespace.feature.templates;
    var buildHtml = function(type) {
        var tmpHtml = t.input1 + t.commonInput + t.input2;
        container.append(tmpHtml);
    }
    var init = function() {
        buildHtml();
    }
    return {
        init : init,
    };
    }();
    namespace.feature.module.init();
    });
    

就在我的头顶上。

你可以把模板写成构建字符串的函数。

input3 : function(param) {
    return '<div>' + param + '</div>'
}

:

var tmpHTML = t.input1 + t.input2 + t.input3(t.commonInput);

另外,我喜欢在构建HTML时构建自己的DOM对象。并避免使用硬编码字符串。

http://mg.to/2006/02/27/easy-dom-creation-for-jquery-and-prototype

我不确定你的确切问题是什么,但就更好的选择而言,我建议使用jQuery模板。

下面是所有不同模板引擎及其性能的基准测试页面:http://jsperf.com/dom-vs-innerhtml-based-templating

你可以查看版本来找到不同的引擎组合,也可以在不同的浏览器上运行它们来查看速度差异。

Update:原来的jquery模板项目不再激活。这是旧项目的新家:https://github.com/BorisMoore/jquery-tmpl

我将不再推荐jquery模板,因为现在有更好的选择。上次我检查的时候,linkedIn分支的dustJs似乎是最有希望的一个。