为什么在 location.reload() 之后使用 onclick 返回 false? [英] Why return false after location.reload() using onclick?
问题描述
我正在制作一个 JavaScript 应用程序,我使用该方法 location.reload().我在 onclick
事件处理程序中使用 location.reload()
来重置页面,这个答案说你需要 return false;
location.reload()
和 onclick
之后:如何使用 JavaScript 重新加载页面.
location.reload();
有关详细信息,请参阅此 MDN 页面.
如果你在 onclick
之后刷新,那么你需要在之后直接返回 false
location.reload();返回假;
为什么你应该在方法 location.reload()
之后使用 onclick
来return false;
?
如果事件侦听器附加到链接,则单击该链接将导致转到另一个页面而不是重新加载页面.return false
将阻止内联事件处理程序和 onclick
属性中的默认操作.
没有返回false
:
document.querySelector('a').onclick = function() {location.reload();}
点击</a>
预>
随着return false
:
console.log('Loaded', new Date);document.querySelector('a').onclick = function() {location.reload();返回假;}
点击</a>
预>
在现代 JavaScript 中,将使用 addEventListener
和 event.preventDefault()
代替.
document.querySelector('a').addEventListener('click', function(e){e.preventDefault();location.reload();});
I'm making a JavaScript app where I use the method location.reload(). I'm using location.reload()
in a onclick
event handler to reset the page, and this answer says that you need to return false;
after location.reload()
with 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;
Why should you return false;
after method location.reload()
using onclick
?
If the event listener is attached to a link, then clicking the link will result in going to another page instead of reloading the page. return false
will prevent the default action in an inline event handler and the onclick
property.
Without return false
:
document.querySelector('a').onclick = function() {
location.reload();
}
<a href="https://www.example.com">Click</a>
With return false
:
console.log('Loaded', new Date);
document.querySelector('a').onclick = function() {
location.reload();
return false;
}
<a href="https://www.example.com">Click</a>
In modern JavaScript, addEventListener
and event.preventDefault()
would be used instead.
document.querySelector('a').addEventListener('click', function(e){
e.preventDefault();
location.reload();
});
这篇关于为什么在 location.reload() 之后使用 onclick 返回 false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!