简体   繁体   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);
});

When e.preventDefault() is removed, the hash tag will appear after like localhost/page1.html# , but when e.preventDefault() is added, e.originalEvent.state will appear as null 当删除e.preventDefault() ,哈希标签将在localhost/page1.html#之后出现,但是当添加e.preventDefault()时, e.originalEvent.state将显示为null

<a href="#" class="button">Click me</a>

What is the problem? 问题是什么? How do I solve it? 我该如何解决?

EDITED: 编辑:

When the button is pressed, the address bar updated(That's good). 按下按钮后,地址栏就会更新(很好)。 However, when I hit the back button, the state object appears as null(It suppose to show {url: 'index.html'}) 但是,当我按下“后退”按钮时,状态对象显示为null(它应该显示{url:'index.html'})

What you are seeing isn't a bug, it's the intended behavior. 您所看到的不是错误,而是预期的行为。

When you first load the page, the state is / and the state object is null. 首次加载页面时,状态为/ ,状态对象为null。 when you click on the anchor tag with preventDefault , the state is changed to /page1.html and is given an object to store. 当您使用preventDefault单击锚标记时,状态将更改为/page1.html并被赋予要存储的对象。 Now, when you press back button, the popstate event happens after the state has changed back to / , which doesn't have a state object! 现在,当您按下“后退”按钮时,popstate事件将在状态更改回/之后发生,该状态没有状态对象!

To demonstrate, click the link 3-4 times. 为了演示,请单击链接3-4次。 Now, each time you hit back, originalEvent.state will have an object until you get back to / , which of course doesn't have a state object. 现在,每次您回击时, originalEvent.state都会有一个对象,直到返回到/为止,而该对象当然没有状态对象。

To make the default state have a state object instead of null, use replaceState. 要使默认状态具有状态对象而不是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/ http://jsfiddle.net/Kd3vw/6/

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

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