1

我试图弄清楚History.js,如果你去下面的代码可以工作,index.html但如果你尝试index.html?info直接访问,它会显示索引内容。当有人试图直接访问时,您应该如何检测状态index.html?info?另外,我也不确定我是否正确地执行初始状态。

索引.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>
4

1 回答 1

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();

这有点像 hack,但它会做你想做的事;

于 2013-10-26T20:43:06.000 回答