【问题标题】:HTML templates inside JavaScript file... What am I doing wrong?JavaScript文件中的HTML模板......我做错了什么?
【发布时间】:2011-07-15 01:13:33
【问题描述】:

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

buildHtml 函数当前设置如何正常工作。我卡住的地方是如果......我在模板对象中有另一个变量说'input3',它的标记类似于<div>(exact markup from commonInput)</div>

我尝试将其用作input 3 : '<div>' + this.commonInput + '</div>',但事实证明您不能使用this(explained here) 从内部引用对象属性。

我可以使用完整的 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();
    
    });
    

【问题讨论】:

标签: javascript jquery jquery-templates


【解决方案1】:

就在我头顶。

您可以将模板编写为构建字符串的函数。

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

【讨论】:

  • 谢谢老兄...感谢您的帮助!
  • 您对这种动态创建内容的方法有何看法...您推荐任何其他方法/解决方案。我有一个关于 stackoverflow.com/questions/6685582/… 的问题
【解决方案2】:

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

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

您可以查看修订版以找到不同的引擎组合,并在不同的浏览器上运行它们以查看速度差异。

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

我不再推荐 jquery-templates,因为现在有更好的选择。上次查看时,dustJs by linkedIn fork 似乎是最有希望的一个。

【讨论】:

  • 不幸的是,该链接已失效。也许这就是你说的项目? plugins.jquery.com/loadTemplate
  • 取出链接并替换为正确的链接。您拥有的那个看起来很相似,但与原来的完全不同。
猜你喜欢
  • 2020-02-22
  • 2016-03-08
  • 2014-09-13
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多