更改网址时不会使用<a href=" ">

时间:2016-01-08 07:41:01

标签: javascript jquery html5

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

3 个答案:

答案 0 :(得分:3)

  1. 在onclick中,您有my_function,其中实际的函数名称为my_fnuction

  2. 您需要取消默认行为,如果您的onclick函数返回false,则取消默认浏览器行为。

  3. <强>代码:

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

可能只是阻止了锚标记的默认行为。将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>