繁体   English   中英

事件防止默认值不起作用

[英]event prevent default not working

$(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单击锚标记时,状态将更改为/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/

暂无
暂无

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

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