【问题标题】:Handlebars Error with jQueryjQuery的车把错误
【发布时间】: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


【解决方案1】:

由于&lt;script&gt; 是&lt;div&gt; 内容的一部分,设置.html() 也会从文档中删除&lt;script&gt;,使其无法下次使用。

您只需要compile 和template 一次,因此它不依赖于&lt;script&gt; 的存在。

var galleryTemplate;

function setGalleryTemplate() {
    // compile on-demand, but only once
    if (!galleryTemplate)
        galleryTemplate = Handlebars.compile( $('#gallery-template').html() );

    var projectData = JSON.parse(localStorage.getItem(keyName) );

    $('#Gallery').html( galleryTemplate(projectData) );
}

或者,调整标记使&lt;div&gt; 和&lt;script&gt; 是兄弟而不是父/子,因此&lt;script&gt; 保留在文档中,而&lt;div&gt; 的内容被替换:

<div id="Gallery"></div>
<script id="gallery-template" type="text/x-handlebars-template">
    <!-- ... -->
</script>

【讨论】:

  • 非常感谢!现在我读到了答案,这似乎很容易:)
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 2022-01-18
  • 2015-12-13
  • 1970-01-01
  • 2017-11-21
  • 2018-06-20
  • 2016-12-06
  • 1970-01-01
相关资源
最近更新 更多