【问题标题】:Can jQuery template bind to a raw arrayjQuery模板可以绑定到原始数​​组吗
【发布时间】:2011-08-31 15:31:57
【问题描述】:

给定

<div id="place_holder" />

<script id="template" type="text/x-jquery-tmpl">
WHAT DO I PUT HERE
</script>

var array_of_ints = [1,2,3]

$( "#template" )
        .tmpl( array_of_ints   )
        .appendTo( "#place_holder" );

我可以在模板中放入什么来获得?

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

【问题讨论】:

    标签: jquery jquery-templates


    【解决方案1】:
    <div id="place_holder" />
    
    <script id="template" type="text/x-jquery-tmpl">
        {{= $data}}
    </script>
    
    var array_of_ints = [1,2,3]
    
    $( "#template" )
        .tmpl( array_of_ints   )
        .appendTo( "#place_holder" );
    

    {{= $data}} 可以在任何地方使用(${} 不能在模板中的字符串中使用)

    【讨论】:

    • ${} 在模板中的字符串中不起作用是什么意思?你能举一个例子,{{= $data}} 有效,但 ${} 无效?
    • 设置名称和src等标签属性
    【解决方案2】:
    <ul id="place_holder">
    </ul>
    
    <script id="template" type="text/x-jquery-tmpl">
        <li>${}</li>       
    </script>
    
    var array_of_ints = [1,2,3]
    
    $("#template")
        .tmpl(array_of_ints)
        .appendTo( "#place_holder" );
    

    【讨论】:

      【解决方案3】:

      ${} 不适用于字符串数组 ['A String','Another String','Yet Another String'] ,但 {{= $data}} 可以。谢谢!

      【讨论】:

        【解决方案4】:

        您想查看{{each}} 模板标签。

        在这种情况下,我不认为 jQuery.tmpl 真的是最好的方法。在我看来,使用标准的for 循环会容易得多。

        var array_of_ints = [1,2,3];
        
        //creates the ul
        var ul = $('<ul></ul>');
        
        //creates the LI's
        for(var i = 0; i < array_of_ints.length; i++){
            ul.append('<li>' + array_of_ints[i] + '</li>');
        }
        
        //adds to the placeholder
        $('#placeholder').append(ul);
        

        http://jsfiddle.net/LeKYu/

        【讨论】:

        • 问题是问是否可以使用jQuery.tmpl来完成
        • @Michael Wolfenden:我明白这一点,这就是我发布{{each}} 模板标签链接的原因。我建议更改您的示例,因为为此使用 jQuery.tmpl 完全没有意义。一个更现实的例子会更好地为您和任何未来的读者服务。
        • @Michael Wolfdenden:我也相当确定您无法访问根对象。它所做的是对数组中的每个对象/值,它调用模板,而不是用数组调用模板。
        猜你喜欢
        • 2020-04-07
        • 1970-01-01
        • 1970-01-01
        • 2017-11-26
        • 1970-01-01
        • 2016-09-30
        • 1970-01-01
        • 1970-01-01
        • 2010-10-29
        相关资源
        最近更新 更多