admin管理员组文章数量:1405392
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
-
1
onClick='my_function()'
andfunction my_fnuction()
?? – Mi-Creativity Commented Jan 8, 2016 at 7:46
3 Answers
Reset to default 5In onclick you have
my_function
where as the actual function name ismy_fnuction
.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>
本文标签: javascriptchange URL without reloading the page with lta hrefquot quotgtStack Overflow
版权声明:本文标题:javascript - change URL without reloading the page with <a href=" "> - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744213517a2595531.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论