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
答案 0 :(得分:3)
在onclick中,您有my_function
,其中实际的函数名称为my_fnuction
。
您需要取消默认行为,如果您的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>
答案 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>