简体   繁体   English

JavaScript重定向仅刷新页面

[英]Javascript redirect is only refreshing page

I have a javascript function that looks like: 我有一个javascript函数,看起来像:

function logout() {

alert('logging out 2');
window.location.replace("http://stackoverflow.com");

}

The alert pops up but the page refreshes when I want it to go to stackoverflow.com (for testing purposes). 当我希望它进入stackoverflow.com(出于测试目的)时,会弹出警报,但页面会刷新。 Why would this be? 为什么会这样呢?

My guess is you are not cancelling the click event of the element that is calling the function so the page is refreshing. 我的猜测是您没有取消正在调用该函数的元素的click事件,因此页面正在刷新。 Cancel the click event. 取消点击事件。

onclick="logout(); return false;"

or use preventDefault 或使用preventDefault


From the comments 从评论

$('#logout').click(function(e) {e.preventDefault(); logout(); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM