我是编程新手,尤其是 Handlebars 。我的 html 文件中有一个加载了 jquery 和 handlebars 组合的 div。我在它上面有标签。单击选项卡时,我想将所有内容重新加载到新内容。内容相似(结构相同),但标签、图像等必须更改。我尝试在 handlebars.js 中使用部分。 这是示例代码。
<script type="text/x-handlebars-template" id="all-handlebar">
{{#each tabs}}
<div id=tab{{@index}}>{{this.text}}</div>
{{/each}}
<div id="tab-content">{{> tabContentPartial}}
</script>
<script type="text/x-handlebars-template" id="tab-content-partial">
<div id="mycontent">
<div id="text">{{mycontent.text}}</div>
<div id="text">{{mycontent.image}}</div>
</div>
</script>
<script type="text/javascript">
source=$("#all-handlebar").html();
var template = Handlebars.compile(source);
Handlebars.registerPartial("tabContentPartial", $("#tab-content-partial").html())
var context = {
mycontent : {
text="something that has to change everytime I click on a different tab",
image="idem"
};
var html = template(context);
$("body").html(html);
</script>
它第一次加载很好,但是当我单击选项卡时,我要求他重新注册 tab-content-partial 脚本并且它不再存在,因为它已在我的代码中更改为 HTML block 。如何使用新内容重用和重新加载我的部分脚本?
非常感谢!
最佳答案
您的代码中缺少选项卡切换部分以及您检索数据的方式,因此我只能告诉您在收听选项卡切换的地方需要做什么。
为此你只需要编译你的#tab-content-partial
你不需要做太多改变:
var source=$("#all-handlebar").html();
var contentSrc=$("#tab-content-partial").html();
var template = Handlebars.compile(source);
var contentTemplate = Handlebars.compile(contentSrc);
//because you already have a compiled version of your content template now you can pass this as partial
Handlebars.registerPartial("tabContentPartial", contentTemplate);
var context = {
mycontent : {
text : "something that has to change everytime I click on a different tab",
image : "idem"
}
};
var html = template(context);
$("body").html(html);
然后在你需要改变内容的时候,你只需将内容的数据传递给内容模板,然后替换#tab-content
的内容> 有了新的结果。
这样您还可以创建不同的内容模板。
//replace the content with the result of the template
$("#tab-content").html( contentTemplate(newContent) );
我希望这就是您要找的东西,如果没有请随时询问。
关于jquery - 重新加载部分 Handlebars ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17407226/