Javascript 带有handlebar.js的多个模板
我不熟悉javascript和库,所以这可能是一个简单的问题。我正在尝试使用handlebar.js模板引擎和jQuery制作几个简单的网页。我经常遇到的问题是制作多个页面。到目前为止,我有一个不同名称的主页。每个名称上都有一个jqueryclick函数。如果我单击一个名称,我只使用jQuery来更改当前页面。所以,基本上,如果你点击一个名字,你会得到一个新的模板,上面有这个人的图片列表,但是在同一个页面上显示index.html。问题是,如果您想返回到第一个视图,“返回”按钮现在不起作用。我的结构是否有误?链接是否应该发送到另一个页面和另一个模板?如果是这样,我如何根据按下的链接生成模板Javascript 带有handlebar.js的多个模板,javascript,jquery,libraries,handlebars.js,Javascript,Jquery,Libraries,Handlebars.js,我不熟悉javascript和库,所以这可能是一个简单的问题。我正在尝试使用handlebar.js模板引擎和jQuery制作几个简单的网页。我经常遇到的问题是制作多个页面。到目前为止,我有一个不同名称的主页。每个名称上都有一个jqueryclick函数。如果我单击一个名称,我只使用jQuery来更改当前页面。所以,基本上,如果你点击一个名字,你会得到一个新的模板,上面有这个人的图片列表,但是在同一个页面上显示index.html。问题是,如果您想返回到第一个视图,“返回”按钮现在不起作用。我的
$(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。如果使用,有一种相当简单的方法可以让后退/前进按钮工作 因此,它的基本工作原理如下:
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);
有些事情可能需要更改,但这是我通常用于此类任务的一般工作流