简体   繁体   中英

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

<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'})

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. when you click on the anchor tag with preventDefault , the state is changed to /page1.html and is given an object to store. Now, when you press back button, the popstate event happens after the state has changed back to / , which doesn't have a state object!

To demonstrate, click the link 3-4 times. 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.

To make the default state have a state object instead of null, use 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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