相关疑难解决方法(0)

带有history.pushState和popstate的Ajax - 当popstate state属性为null时,我该怎么办?

我正在尝试使用ajax加载内容的HTML5历史API.

我有一堆通过相关链接连接的测试页面.我有这个JS,它处理这些链接的点击.当单击链接时,处理程序获取其href属性并将其传递给ajaxLoadPage(),该页面将所请求页面中的内容加载到当前页面的内容区域中.(我的PHP页面设置为在正常请求时返回完整的HTML页面,但只有一大块内容,如果?fragment = true附加到请求的URL.)

然后我的click处理程序调用history.pushState()以在地址栏中显示URL并将其添加到浏览器历史记录中.

$(document).ready(function(){

    var content = $('#content');

    var ajaxLoadPage = function (url) {
        console.log('Loading ' + url + ' fragment');
        content.load(url + '?fragment=true');
    }

    // Handle click event of all links with href not starting with http, https or #
    $('a').not('[href^=http], [href^=https], [href^=#]').on('click', function(e){

        e.preventDefault();
        var href = $(this).attr('href');
        ajaxLoadPage(href);
        history.pushState({page:href}, null, href);

    });

    // This mostly works - only problem is when popstate happens and state is null
    // e.g. when we try to go back …
Run Code Online (Sandbox Code Playgroud)

javascript jquery html5 browser-history html5-history

21
推荐指数
3
解决办法
4万
查看次数

在反应 js 上显示浏览器后退按钮事件的警报

我必须在 React js 上的浏览​​器返回事件上显示警报。我曾尝试使用 ,addEventListener但我不确定将代码放置在 React 页面中的何处。我应该放置在任何生命周期钩子中还是在渲染中?我不知道。请帮帮我。

reactjs

9
推荐指数
3
解决办法
1万
查看次数

Javascript历史状态不正确

我正在尝试使用填充当前所选选项卡的索引

history.pushState({tabSelected: 1}, null, "");
Run Code Online (Sandbox Code Playgroud)

我有一个jquery中popstate事件的处理程序,它以编程方式切换jquery ui选项卡.

 $(window).bind("popstate", function(event) {
                               var state = event.originalEvent.state;
                               ...
                            }
Run Code Online (Sandbox Code Playgroud)

这工作正常,浏览器和我可以使用后退和前进按钮在选项卡之间切换.也适用于两层标签.

但在某些情况下,我想将其他状态推送到堆栈.所以我做了以下事情:

 var content = { targetId : id,
                  targetContent : $("#myDivId").html()
               };
 $.extend(content, {tabSelected: currentTab});
 history.pushState(content, null, "");
Run Code Online (Sandbox Code Playgroud)

我把它推到历史之前和之后看起来都很好.检查console.log(history.state); 还尝试检查chrome控制台.

但是在我的popstate处理程序中,我没有在对象event.originalEvent.state上看到targetId,tabSelected属性.我在对象上看到tabSelected的正确值,但由于某种原因,我看到了一个削减状态.

检查Chrome和Firefox.无法获得正确的内容.什么想法可能是错的?提前致谢.

更新

还尝试在每个pushstate上递增一个全局变量并将其添加到状态.事实证明,对于特定情况,我提到全局变量变为值48而不是49意味着它正在拾取最后一个事件.我没有看到我的popstate处理程序被调用.不知道发生了什么.

另一个更新

当我调用history.pushState(content,null,"")两次时它可以正常工作.(只在一个地方,在另一个地方,我仍然称它为一次).看起来由于某种原因,浏览器返回的是最后一个状态.显然我的代码有问题,因为这个解决方法适用于chrome和firefox.

jquery html5 pushstate html5-history popstate

7
推荐指数
0
解决办法
7368
查看次数