5

我正在尝试了解有关 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() 函数从未被调用,只是呈现为字符串。我一时兴起尝试将其包装在 {{ }} 中,但没有运气。有谁可以帮忙吗?

4

2 回答 2

8

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

<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>
于 2011-01-19T16:38:19.227 回答
2

我不确定您的 objectToString 位于何处,但如果您在此处看到参考资料,您会看到他们在 .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> 

你可以在这里看到它。

于 2011-01-19T08:25:58.847 回答