【问题标题】:change URL without reloading the page with <a href=" ">更改 URL 而不用 <a href=" "> 重新加载页面
【发布时间】:2016-04-12 19:50:29
【问题描述】:

对于修改URL而不重新加载页面我们可以使用:

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

但如果我尝试使用 &lt;a&gt; 元素:

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

}
 </script>

它不起作用,那么我怎样才能同时使用&lt;a&gt; 元素和window.history.pushState() 呢? 像twitter和facebook一样,用户可以点击右键在新窗口中打开网址,直接点击获取页面和更改网址,无需重新加载

【问题讨论】:

  • onClick='my_function()'function my_fnuction() ??

标签: javascript jquery html


【解决方案1】:
  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>

【讨论】:

  • @Mi-Creativity 错过了它。谢谢。已更新。
  • 不是你的错,在帖子里,我很抱歉
【解决方案2】:

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

解决方法也解释here

【讨论】:

    【解决方案3】:

    可能只是阻止锚标记的默认行为。对事件返回 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-20
      • 2016-01-12
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 2011-04-08
      相关资源
      最近更新 更多