简体   繁体   中英

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

For modify the URL without reloading the page we can use:

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

but if I try it with <a> element :

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

}
 </script>

It will not work, So how can I use <a> element and window.history.pushState() together? Like twitter and Facebook, user can click on the right button to open the URL in new window, and direct click to get pages and change the URL without reloading

  1. In onclick you have my_function where as the actual function name is my_fnuction .

  2. You need to cancel the default behaviour, If your onclick function returns false the default browser behaviour is cancelled.

Code:

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

add return false; make it so that href is not executed, also add return to your onclick value:

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

solution is also is explained here

Probably just preventing the default behavior of anchor tag. Returning false to the event

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

Or using 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>

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