我正在制作 JavaScript 我使用方法 location.reload() 的应用程序.方法location.reload()
位于 onclick
重置页面的事件处理程序,这个答案说你需要 return false;
在 location.reload()
之后与 onclick
: How to reload a page using JavaScript .
location.reload();See this MDN page for more information.
If you are refreshing after an
onclick
then you'll need to return false directly afterlocation.reload(); return false;
你为什么要
return false;
方法后location.reload()
使用 onclick
?
最佳答案
如果事件监听器附加到链接,则单击该链接将导致转到另一个页面而不是重新加载页面。 return false
将阻止内联事件处理程序中的默认操作和 onclick
属性(property)。
没有 return false
:
document.querySelector('a').onclick = function() {
location.reload();
}
<a href="https://www.example.com">Click</a>
与
return false
:console.log('Loaded', new Date);
document.querySelector('a').onclick = function() {
location.reload();
return false;
}
<a href="https://www.example.com">Click</a>
在现代 JavaScript 中,
addEventListener
和 event.preventDefault()
将被使用。document.querySelector('a').addEventListener('click', function(e){
e.preventDefault();
location.reload();
});
关于javascript - 为什么使用 onclick 在 location.reload() 之后返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67328296/