我正在使用 history.js 在 AJAX 产品页面上启用后退/前进浏览器导航。AJAX 功能基于单击产品类别。
我的这个工作很好 - 除了我遇到的一个问题。第一页没有存储在历史记录中。这是我的代码:
HTML:
<ul class="category">
<li><a href="/category/5">Category 5</a></li>
<li><a href="/category/10">Category 10</a></li>
</ul>
JS:
$(document).ready(function(){
var
History = window.History,
State = History.getState();
$('.category a').click(function(){
var path = $(this).attr('href');
var title = $(this).next().text();
var category = $(this).attr('data-cat');
History.pushState({category: category}, title, path);
return false;
});
});
History.Adapter.bind(window, 'statechange', function() {
var State = History.getState();
var category = State.data.category;
myAjaxFunction(category); // function which refreshes the product container
});
现在假设我加载了 URL://mysite/category/10
然后我点击类别 5 - 我得到 URL://mysite/category/5
然后我单击“后退”按钮 - URL 不会更改,并且 AJAX 函数会返回不正确的结果集
我做了一个console.log,它告诉我“State.data.category”是未定义的。
看起来初始页面没有存储在历史会话中,我尝试在页面加载时强制 History.pushState 但这意味着在页面加载时也会触发“statechange”事件,这是不必要的。
有没有人对如何解决这个问题有任何想法?