事件阻止默认值不起作用

event prevent default not working

本文关键字:不起作用 默认值 事件      更新时间:2023-09-26
$(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()后,哈希标签将显示在 like 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,请使用 替换状态。

$(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/