簡體   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