簡體   English   中英

更改URL而不用重新加載頁面

[英]change URL without reloading the page with <a href=“ ”>

要在不重新加載頁面的情況下修改URL,我們可以使用:

window.history.pushState('page2', 'Title', '/page2.php');

但是如果我嘗試使用<a>元素:

<a onClick='my_function()' href='/page2.php'> Click Here </a>
<script>
function my_fnuction(){
    window.history.pushState('page2', 'Title', '/page2.php');

}
 </script>

這將無法正常工作,那么如何將<a>元素和window.history.pushState()一起使用? 像twitter和Facebook一樣,用戶可以單擊右鍵在新窗口中打開URL,然后直接單擊以獲取頁面並更改URL,而無需重新加載

  1. 在onclick中,您具有my_function ,其中實際函數名稱為my_fnuction

  2. 您需要取消默認行為,如果onclick函數返回false,則默認瀏覽器行為將被取消。

碼:

<a onClick='return my_function()' href='/page2.php'> Click Here </a>
<script>
function my_function(){
    window.history.pushState('page2', 'Title', '/page2.php');
    return false;
}
 </script>

添加return false; 使其不會被執行href ,還可以在您的onclick值中添加return

<a onClick='return my_function()' href='/page2.php'> Click Here </a>
<script>
function my_function(){
    window.history.pushState('page2', 'Title', '/page2.php');
    return false;
}
</script>

解決方案也在這里解釋

可能只是防止錨標記的默認行為。 將false返回事件

<a onClick='return my_function()' href='/page2.php'> Click Here </a>
<script>
function my_function(){
    window.history.pushState('page2', 'Title', '/page2.php');
return false;

}
 </script>

或使用prevent default:

<a onClick='my_function(event); ' href='/page2.php'> Click Here </a>
<script>
function my_function(e){
    window.history.pushState('page2', 'Title', '/page2.php');
e.preventDefault();
}
 </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM