0

这个Demo我要点击前进到content(index.php?id=id)点击回到subject(index.php)。

Q1。(index.php?id=id) 直接链接content页面不可用,它会显示 (index.php) subject,为什么?

Q2。第二次点击后退(前进>后退>前进>后退)然后url将停止更改,为什么?(Safari 5) 更新:使用window.onpopstateurl 工作正常。不会得到这个错误。


任何建议将不胜感激。

$(window).bind('popstate', function(){
    $.ajax({
        url:location.pathname,
        success: function(data){
            $('.container').html(data);
        }
    });
});

演示

$('.subject').click(function(){
    $.ajax({
        url: 'index.php?id=' + $(this).attr('rel'),
            success: function(data){
                $('.container').html(data);
            }
    });
    var pageurl;
    pageurl = 'index.php?id=' + $(this).attr('rel');
    if(pageurl != window.location){
        window.history.pushState({path: pageurl}, "", pageurl);
    }
    return false;
});

索引.php

<div class="container">
    <?php
        if($_GET['id']){
           ...
            print"<div class="content"></div>";
        }
        else{
           ...
           print"<div class="subject" rel="id"></div>"
        }
    ?>
</div>
4

2 回答 2

1

您只需要使用 ajax 获取页面内容(即您的场景的主题)并将其显示在您的页面容器中。考虑一下您是否在“index.php”中并点击了一个主题……所以您的 url 更改为“index.php?id=7”。现在您正在单击返回.. 在“popstate”事件中,“location.pathname”给出了“http://host/index.php”。就是这样,使用ajax从'location.pathname'中获取数据并显示它。

$(window).bind('popstate', function(){
    $.ajax({
        url:location.pathname,
        success: function(data){
            $('.content').html(data);
        }
    });
});
于 2012-12-14T08:39:06.067 回答
1

popstate 事件处理程序将接收一个事件对象,其中包含您传递给 pushState的状态。可以通过event.stateHere's the event interface definition访问它。这是一些演示代码来说明这个概念。

window.addEventListener("popstate", function(event) {
if( event.state !== null )    
    alert('Browser back button was clicked, state returned ' + JSON.stringify( event.state ) ); 
};
于 2012-12-13T22:21:57.363 回答