简体   繁体   English

如何使用HTML5历史记录使前进按钮在此示例上起作用?

[英]How to make forward button work on this example using HTML5 history?

In this example we manage to make back button work but forward button seem to be a problem, when forward button is pressed, #modal should reappear but it did not. 在此示例中,我们设法使后退按钮起作用,但前进按钮似乎是一个问题,当按下前进按钮时, #modal应该重新出现,但没有出现。 Any idea to fix it? 有解决的办法吗?

 $(window).bind('popstate', function() { $('#modal').hide(); }); $(".view").click(function() { history.pushState(null, null, null); $("#modal").show(); }); 
 #modal { position: relative; display: none; height: 100px; width: 100px; background-color: grey } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button class="view">Click</button> <div id="modal"></div> 

Here is JSBin 这是JSBin

Thanks! 谢谢!

You can use "hash" instead of "history" 您可以使用“哈希”代替“历史记录”

$(window).bind('popstate', function() {
  if(location.hash.indexOf('#modal') != -1)
      $('#modal').show();
  else
    $('#modal').hide();
});

$(".view").click(function(){
  location.hash ='#modal';
  $("#modal").show();
});

This is a demo 这是一个演示

By pushing all null onto the history you aren't coupling the state / view of the page in any way. 通过将所有null推入历史记录,您不会以任何方式耦合页面的状态/视图。 Are you aware that the popstate event is also fired when you move forward along the stack too? 您是否知道当您沿着堆栈前进时也会触发popstate事件?

Most people tend to use relative URLs (or fragments) known as "routing" to resolve history / content but you can also use the first parameter of pushState to add data - how you manage this mechanism on a larger scale is out of scope but a simple example would be as follows: 大多数人倾向于使用称为“路由”的相对URL(或片段)来解析历史记录/内容,但您也可以使用pushState的第一个参数添加数据-大规模管理此机制的方式超出了范围,但一个简单的例子如下:

$(window).bind('popstate', function() {
    var state = history.state || {};
    state.openModal ? $('#modal').show() : $('#modal').hide();
});

$(".view").click(function(){
    $('#modal').show();
    history.pushState({ openModal: true });
});

» demo »演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM