更改URL而不使用<a href="">

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

本文关键字:quot href gt lt 更改 URL      更新时间:2023-09-26

对于在不重新加载页面的情况下修改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,也将return添加到您的onclick值:

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

或者使用防止默认:

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