$(function(){
$('.button').click(function(e){
e.preventDefault();
history.pushState({url: 'index.html'},'','page1.html');
});
});
$(window).bind('popstate', function(e){
console.log(e.originalEvent);
});
当 e.preventDefault()
被删除时,哈希标签将出现在 localhost/page1.html#
之后,但是当 e.preventDefault() 时添加
后,e.originalEvent.state
将显示为 null
<a href="#" class="button">Click me</a>
有什么问题吗?怎么解决?
编辑:
按下按钮时,地址栏会更新(这很好)。但是,当我点击后退按钮时,状态对象显示为 null(它应该显示 {url: 'index.html'})
最佳答案
您所看到的不是错误,而是预期的行为。
第一次加载页面时,状态为/
,状态对象为null。当您单击带有 preventDefault
的 anchor 标记时,状态将更改为 /page1.html
并给出一个要存储的对象。现在,当您按后退按钮时,popstate 事件会在状态更改回 /
后发生,而 /
没有状态对象!
要进行演示,请单击链接 3-4 次。现在,每次您回击时,originalEvent.state
都会有一个对象,直到您返回 /
,当然它没有状态对象。
要使默认状态具有状态对象而不是 null,请使用replaceState。
$(function(){
$('a').click(function(e){
e.preventDefault();
history.pushState({url: 'index.html'},'','page1.html');
});
});
$(window).bind('popstate', function(e){
console.log(e.originalEvent);
});
// give the current state a state object
history.replaceState({url: 'index.html'},'','');
关于javascript - 事件防止默认不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25071644/