History.js - 直接访问时检测状态?

时间:2013-10-26 20:35:40

标签: javascript jquery history.js

我正在尝试找出History.js,如果您转到index.html,以下代码可以正常工作,但如果您尝试直接访问index.html?info,则会显示索引内容。当某人试图直接访问index.html?info时,你究竟应该如何检测状态?另外,我不确定我是否正确地做了初始状态。

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>title</title>
    <script src="js/jquery-1.10.2.min.js"></script>
    <script src="js/jquery.history.js"></script>
</head>
<body>

    <div id="content"></div>

    <script>
        History.Adapter.bind(window, 'statechange', function() {
            var id = History.getState().data.id;

            if (id == "index") {
                $('#content').html('<button id="btn" type="button">get info</button>');
                $('#btn').click(function() {
                   History.pushState({ id: "info" }, '', '?info'); 
                });
            }

            if (id == "info") {
                $('#content').html('here is some info');
            }
        });

        History.pushState({ id: "index" }, '', '?index'); //do this otherwise nothing loads on first run
    </script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

嗯,你总是在你的例子中推动索引状态。你可以做的是这样的:而不是History.pushState写:

var p = window.location.search.replace( "?", "" ); //this gets you the parameter
History.replaceState({id: p}, '', '?'+p);

但是,历史状态在刷新时保留,因此在刷新页面时statechange事件不会触发,因为状态不会改变。

所以要解决这个问题,你需要这样的东西:

var historyFired = false;

function onHistory() {
  //put code previously in your statechange hanlder here
  historyFired = true;
}

History.Adapter.bind(window,'statechange',onHistory);

var p = window.location.search.replace( "?", "" ); //this gets you the parameter
History.replaceState({id: p}, '', '?'+p);

if (!historyFired) onHistory();

这有点像黑客攻击,但它可以做你想做的事情;