最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - change URL without reloading the page with <a href=" "> - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question edited Jan 8, 2016 at 7:48 Mi-Creativity 9,66410 gold badges40 silver badges48 bronze badges asked Jan 8, 2016 at 7:41 MazinMazin 1432 silver badges9 bronze badges 1
  • 1 onClick='my_function()' and function my_fnuction() ?? – Mi-Creativity Commented Jan 8, 2016 at 7:46
Add a ment  | 

3 Answers 3

Reset to default 5
  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>
发布评论

评论列表(0)

  1. 暂无评论