Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery时出现手柄错误_Javascript_Jquery_Json_Handlebars.js - Fatal编程技术网

Javascript 使用jQuery时出现手柄错误

Javascript 使用jQuery时出现手柄错误,javascript,jquery,json,handlebars.js,Javascript,Jquery,Json,Handlebars.js,我对此功能有问题: function setGalleryTemplate() { var projectData = JSON.parse(localStorage.getItem(keyName) ), template = Handlebars.compile( $('#gallery-template').html() ); $('#Gallery').htm

我对此功能有问题:

            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也不起作用,不能追加新内容。

由于是的内容的一部分,设置.html也将从文档中删除,使其呈现为不可供下次使用

您可能希望只编译模板一次,因此它不依赖于的存在

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) );
}
或者,调整标记,使和是同级而不是父/子级,以便在替换的内容时保留在文档中:

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

如果未定义正在传递给handlebar.compile,则$'gallery-template'至少会在某些时候找不到任何元素。您也可以共享相关的标记吗?而且,该标记是否被脚本的其他部分更改?除非通过此函数,否则标记永远不会更改。我发现Undefined非常奇怪,因为它每次都与.appendtemplateprojectData一起工作。非常感谢!现在我读了答案,这似乎是一个不需要动脑筋的问题: