javascript - JavaScript 事件函数在每个页面加载时运行一个
问题描述
body
我在页面的 HTML 部分中放置了一个事件 javascript 函数。
<script type="text/javascript">
function CookiebotCallback_OnAccept() {
window.location.reload(true);
if (Cookiebot.consent.statistics)
{
}
}
</script>
此脚本会导致无限刷新,因为每次加载页面时都会运行该函数。我该怎么做才能使此功能仅在调用时才运行,而不是在每个页面加载时自动运行?
解决方案
localStorage
我的解决方案是在or中创建一个标志变量sessionStorage
,然后检查是否已经有该变量,跳过调用重新加载。
<script type="text/javascript">
function CookiebotCallback_OnAccept() {
if(!sessionStorage.getItem('isReloaded')) {
sessionStorage.setItem('isReloaded', true);
window.location.reload(true);
if (Cookiebot.consent.statistics)
{
}
}
}
</script>
// you can also clear the variable to trigger the reload again.
// By: sessionStorage.removeItem('isReloaded');
// Note: the sessionStorage will be cleared each time you close the browser,
// while localStorage is only by uninstalled the browser or manually.
推荐阅读
- node.js - Mongo Aggregate - 获取查询结果中出现多个值的次数
- c# - 使用 C# 跟踪 DISM 进度 - 在 Windows 10 中工作,但不在 WinPE 中
- pandas - 如何将数字列(没有日历日期)转换为日期时间
- mongodb - 非管理员用户的稳定/mongodb-replicaset helm chart 身份验证错误
- scala - 究竟什么是幺半群同态?
- vb.net - 错误在代码“CheckBoxActive.Checked = Convert.ToBoolean(ds1.Tables(0).Rows(0)(3).ToString())”中显示“String is not a valid Boolean”
- debugging - Firefox 在使用开发者工具时挂起
- mongodb - mongo:查找未取代的文档
- php - PHP(取消)在比较它们时从2个动态数组中选中一个复选框
- python - 在没有更多页面 Python 后中断循环