我是 javascript 和库的新手,所以这可能是一个简单的问题。我正在尝试使用 handlebars.js 模板引擎和 jQuery 制作几个简单的网页。我一直遇到的问题是制作多个页面。到目前为止,我有一个具有不同名称的主页。每个名字都有一个 jquery click 函数。如果我单击一个名称,我只是使用 jQuery 来更改当前页面。所以基本上,如果你点击一个名字,你会得到一个新模板,其中包含该人的图片列表,但在同一页面上说 index.html。这样做的问题是,如果您想返回到第一个 View ,“后退”按钮现在不起作用。我的结构不正确吗?链接是否应该发送到另一个页面和另一个模板?如果是这样,我如何根据按下的链接生成模板。
$(document).ready(function(){
var source = $(".some-template").html();
var template = Handlebars.compile(source);
data = { date: "today", firstUsers: [
{firstName: "person1", pictures: ["pic1", "pic2", "pic3"]},
{firstName: "person2", pictures: ["pic1", "pic2", "pic3"]},
{firstName: "person3", pictures: ["pic1", "pic2", "pic3"]},
{firstName: "person4", pictures: ["pic1", "pic2", "pic3"]},
]
};
$(".container").html(template(data))
$("li").click(function(){
var name = $(this).html()
$.each(data.firstUsers, function(i, item){
if(name === item.firstName){
y = item.pictures
return y
};//if function
});//each function
$(".container").hide()
var source = $(".some-script").html();
var template = Handlebars.compile(source);
datas = {namer: name, pictures: y,}
//console.log(datas.pictures)
$(".content").html(template(datas))
});//click function
});//document ready
最佳答案
使用最佳实践,您应该有与每个页面关联的 URL。如果你使用 window.history.pushState ,有一种相当简单的方法可以使后退/前进按钮正常工作。
所以基本上它的工作原理如下:
- 每次加载新模板时,都会推送一个新的浏览器状态。
- 监听
onpopstate
事件,并在它触发时加载适当的模板。
为了可重用性,我将上面的函数分成两个单独的函数:
function loadUser(name) {
var y;
$.each(data.firstUsers, function(i, item){
if(name === item.firstName){
y = item.pictures
return y
};//if function
});//each function
$(".container").hide()
var source = $(".some-script").html();
var template = Handlebars.compile(source);
datas = {namer: name, pictures: y,}
//console.log(datas.pictures)
$(".content").html(template(datas))
window.history.pushState(null, null, name);
}
// Find the name of the user
// TODO: change the regex to match your URL scheme
function popStateResponder() {
var name = window.location.pathname.match(/\w+$/)[0];
loadUser(name);
}
$("li").click(function(){
var name = $(this).html(),
loadUser(name);
});//click function
$(window).on('popstate', popStateResponder);
可能需要更改一些内容,但这是我通常用于此类任务的一般工作流程。
关于javascript - 带有 handlebars.js 的多个模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15412885/