【问题标题】:jQuery Template - Executing JS code inside the templatejQuery 模板 - 在模板中执行 JS 代码
【发布时间】:2011-06-11 14:19:18
【问题描述】:

我正在尝试了解有关 jQuery 模板的更多信息,但似乎无法在模板内执行任何 JS 调用。

<script id="log-item" type="text/x-jquery-tmpl">
 {{if title.length }}
   <h3 style="padding-bottom:5px;">${ title }</h3>
 {{/if}}
 objectToString(${ detail });
</script>

请注意,我的 objectToString() 函数从未被调用,只是呈现为字符串。我一时兴起尝试将其包装在 {{ }} 中,但没有运气。有谁可以帮忙吗?

【问题讨论】:

    标签: jquery jquery-templates


    【解决方案1】:

    安东尼,你可以。您调用的方法需要在模板标签内,如下所示:

    <script id="log-item" type="text/x-jquery-tmpl">
     {{if title.length }}
       <h3 style="padding-bottom:5px;">${ title }</h3>
     {{/if}}
     <p>
        Detail: ${ objectToString( detail ) }
     </p>
    </script>
    

    【讨论】:

    • 这更像是我想要的。我可以发誓我试过这个。但是,是的,这看起来很完美
    • +1 - 我用它来获取变量,干得好。现在正在寻找增量和减量:D
    【解决方案2】:

    我不确定您的 objectToString 位于何处,但如果您看到引用 here,您会看到他们在 .tmpl( 方法) 中添加了必要的辅助函数。

    这是一个示例...我试图使其与您的问题相似...

    <!DOCTYPE html> 
    <html> 
    <head> 
      <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
      <title>Test jquery Templates</title> 
      <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script> 
      <script type='text/javascript' src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> 
    </head> 
    <body> 
      <script id="testTemplate" type="text/x-jquery-tmpl"> 
        {{if title.length}}
          <h3>${title}</h3>
          <p>Detail: ${$item.objectToString("detail")}</p>
        {{/if}}
      </script>  
      <div id="bookList"></div> 
      <script type='text/javascript'> 
        $(function(){
          var book = [
            { title: "Goodnight, World!",
              detail: { author: "Jojo Mojo", synopsis : "What the ..." }},
            { title: "Rainbow",
              detail: { author: "Cookie", synopsis : "Huh?" }}
          ];
    
          $("#testTemplate").tmpl(book, {
            objectToString : function(key) {
              var detail = this.data[key];
              return detail.author +  " " + detail.synopsis;
            }
          }).appendTo("#bookList");
      });
      </script> 
    </body> 
    </html> 
    

    你可以看到here

    【讨论】:

    • 确实这就是答案。看起来很疯狂。为什么我不能简单地调用模板中的javascript函数?
    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 2016-11-23
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多