【问题标题】:History.js onpopstate?History.js onpopstate?
【发布时间】:2011-11-02 20:01:28
【问题描述】:

在学习使用 History API 后,我正在尝试实现 History.js。但是我的 popstate 不再工作了。

History.js 中使用什么作为onpopstate?在历史 API 中,您使用 onpopstateevent.state

我需要知道 History.js 中使用了什么。是window.onstatechange,它返回什么?

【问题讨论】:

    标签: javascript html history.js


    【解决方案1】:

    你无法分辨它是来自 push 还是 pop。这是由它的设计决定的。 在推送事件之前你不应该做任何事情。相反,您应该将所有必需的数据传递给第一个参数。

    History.pushState(data,title,url)
    

    然后从 onstatechange 中检索数据并执行一些操作。

    检查这个:https://github.com/browserstate/history.js/issues/47

    【讨论】:

    【解决方案2】:

    基本例子说:

    History.Adapter.bind(window,'statechange',function(){ // code });
    

    this gist(用于 jQuery)使用:

    $(window).bind('statechange',function(){ // code });
    

    【讨论】:

      【解决方案3】:

      您应该使用由 History.js 发明的事件 window.statechange,因为 window.popstate 太笼统了。您可以通过将事件处理程序绑定到它来对其做出反应,通常如下所示:

      History.Adapter.bind(window, 'statechange', function () {
          var state = History.getState();
          // Your code goes here
      });
      

      或者您可以使用路由器抽象,这应该更容易。例如,我写了一个,叫做StateRouter.js。一些简单的示例代码:

      var router = new staterouter.Router();
      // Configure routes
      router
        .route('/', getHome)
        .route('/persons', getPersons)
        .route('/persons/:id', getPerson);
      // Perform routing of the current state
      router.perform();
      // Navigate to the page of person 1
      router.navigate('/persons/1');
      

      我也有a fiddle for demonstration purposes

      【讨论】:

        【解决方案4】:

        尝试将接下来的两个事件添加到您的标签正文中:

        1. onpopstate="(your code)" --> 用于 html5 浏览器
        2. onhashchange="(your code)" --> 用于 html4 浏览器

        如果您遇到任何问题,例如两次运行您的代码,请尝试构建一个询问pushState 是否准备就绪的函数并使用onpopstate。如果不是,在其他情况下,使用onhashchange

        【讨论】:

        • 您可能想扩展此答案,提供实际代码 sn-ps 以清楚起见。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-01
        • 2023-03-20
        • 2011-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        相关资源
        最近更新 更多