【发布时间】:2014-08-31 23:34:06
【问题描述】:
我对此功能有疑问:
function setGalleryTemplate() {
var projectData = JSON.parse(localStorage.getItem(keyName) ),
template = Handlebars.compile( $('#gallery-template').html() );
$('#Gallery').html( template(projectData) );
};
这是 HTML:
<div id="Gallery">
<script id="gallery-template" type="text/x-handlebars-template">
<ul class="field-list">
{{#each this.project.modules}}
<li class="field-item">{{this.id}}</li>
{{/each}}
</ul>
</script>
</div>
点击图片时调用它,它应该显示来自 json 文件的一些细节。如果第一次单击图像,这可以正常工作。如果第二次单击它(或其他图像),我会收到此“错误:您必须将字符串或 Handlebars AST 传递给 Handlebars.compile。您传递了未定义”。
如果 ."html" 被替换为 ".append" ,这并不是我真正想要的。我想“替换”内容(.replaceWith 也不起作用),而不是追加新内容。
【问题讨论】:
-
如果
undefined被传递给Handlebars.compile(),那么至少有几次$('#gallery-template')找不到元素。你也可以分享相关的标记吗?而且,脚本的其他部分是否更改了该标记? -
标记永远不会被这个函数改变。我发现“未定义”很奇怪,因为它每次都与 .append(template(projectData)) 一起工作。
标签: javascript jquery json handlebars.js