问题描述
我处于调试模式,因此我可以看到被击中的页面.
I am in debug mode, so I can see which page is being hit.
当我呼叫window.location
或window.location.replace(..)
时,它会转到页面,然后返回到原始页面!
When I call either window.location
or window.location.replace(..)
it goes to the page, but then back to the originating page!
怎么可能?
解决方案是添加:
window.location.replace(...);
return false;
为什么return false
现在可以使其正常工作?
Why does return false
make this work properly now?
推荐答案
如果此脚本发生在onclick
或onsubmit
事件上,则没有返回或返回true
表示浏览器应采取默认操作用于链接/表单.因此,如果您有onclick
处理程序,例如:
If this script happened on an onclick
or onsubmit
event, then no return or returning true
will indicate that the browser should take the default action for the link/form. So, if you had an onclick
handler like:
<a href="http://www.google.com/" onclick="window.location = 'http://www.yahoo.com/';">
然后,浏览器将转到Yahoo,然后看到它应该执行链接的其他操作(导航到Google).当您指定return false;
时,浏览器知道不执行下一步/默认操作.
Then the browser will go to Yahoo, then see that it should execute the link's other action (navigating to Google). When you indicate return false;
, the browser knows not to execute the next/default action.
<a href="http://www.google.com/" onclick="window.location = 'http://www.yahoo.com/'; return false;">
那么,为什么return false;
可以做到这一点?
So, why does return false;
make this work?
对于任何事件处理程序,返回true
表示继续正常运行,返回false
表示停止尝试处理事件(),尽管有反对使用return false;
的参数.
For any event hander, to return true
indicates to continue as normal and to return false
means to stop trying to handle the event (prevents default handling and stops propagation), though there are arguments against using return false;
.
这篇关于很奇怪!调用window.location或location.replace重定向到页面,然后再次返回!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!