javascript - 事件防止默认不起作用

标签 javascript jquery html

$(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'},'','');

http://jsfiddle.net/Kd3vw/6/

关于javascript - 事件防止默认不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25071644/

相关文章:

javascript - iOS 7 进入全屏模式(添加到主屏幕按钮)

javascript - 如何在Angular中无限迭代动画

javascript - 始终使用 Bower.json 从 git 提取最新版本的代码

javascript - 在alert()完成后提交表单

html - HTML 标签中的 ID 是否允许为空?

javascript - 比较两列中的随机数字集

javascript - 显示/隐藏表格内的所有 tr-s

javascript - 如何在子 ul 上 iqnore mousemove 事件

css - 与 IE8 相比,绝对定位元素在 safari 中显示在不同的位置

html - 为什么我的多列布局在 Firefox 中将所有内容都放在一列中?