我有这个小示例应用程序,我尝试使用历史记录实现路由系统。它作为例外工作,但由于某种原因,我必须按两次后退按钮。如果打开控制台,则可以看到日志。当我按下例如page1和page2,然后按下后退链接时,它会记录page2
两次。为什么?如果我再次按它,它会记录page1
两次。什么?然后它终于回去了。我为什么要按两次?日志为何如此疯狂?我怎样才能使它发挥作用?
<div id="home">Home</div>
<div id="page1">Page1</div>
<div id="page2">Page2</div>
<div id="back">Back</div>
var app = {};
app.router = Backbone.Router.extend({
routes: {
'': 'home',
'page1': 'page1',
'page2': 'page2',
},
home: function () {
console.log('home');
Backbone.history.history.pushState('search');
console.log(Backbone.history.history);
},
page1: function () {
console.log('page1');
Backbone.history.history.pushState('page1');
console.log(Backbone.history.history);
},
page2: function () {
console.log('page2');
Backbone.history.history.pushState('page2');
console.log(Backbone.history.history);
},
});
var router = new app.router();
Backbone.history.start();
$(document).on('click', '#back', function () {
console.log('back');
console.log(Backbone.history.history);
Backbone.history.history.back();
console.log(Backbone.history.history);
router.navigate(Backbone.history.history.state, {trigger: true, replace: true});
});
$(document).on('click', '#home', function () {
router.navigate('home', {trigger: true, replace: true});
});
$(document).on('click', '#page1', function () {
router.navigate('page1', {trigger: true, replace: true});
});
$(document).on('click', '#page2', function () {
router.navigate('page2', {trigger: true, replace: true});
});
答案 0 :(得分:0)
这是否符合您的目的:
$(document).on('click', '#back', function () {
window.history.back();
});
MDN window.history