重定向后运行函数一次
Run function once after redirecting
我正在尝试将访问网站的用户重定向到移动网站。到目前为止,我已经做了这些,但问题是每次加载页面时,函数都会一直运行。这些函数在页面加载后被调用。我是JavaScript初学者。
function redirectPage() {
var runOnce = 0;
if (runOnce == 0 && windowWidth <= 767){
runOnce = 1;
window.location.assign("example.net/mobile-site");
}
else if (runOnce == 0 && windowWidth >= 767){
runOnce = 1;
window.location.assign("example.net/regular-site");
}
}
更新
这就是我所做的,但到目前为止,浏览器一直在加载。
var windowWidth = 0;
$(document).ready(function(){
checkBrowserWidth();
redirectPage();
});
function checkBrowserWidth() {
windowWidth = window.outerWidth;
}
function redirectPage() {
if (typeof(Storage) != 'undefined') {
// Store value
localStorage.setItem('runOnce', 0);
}
var runOnce = localStorage.getItem('runOnce');
if (runOnce == 0 && windowWidth <= 767){
localStorage.setItem('runOnce', 1);
window.location.assign("example.net/mobile-site");
}
else if (runOnce == 0 && windowWidth >= 767){
localStorage.setItem('runOnce', 1);
window.location.assign("example.net/regular-site");
}
}
您的方法存在几个问题。
范围
JavaScript具有函数范围。这意味着runOnce将始终是redirectPage
函数之外的undefined
。因此,每个呼叫都会将runOnce
作为undefined
。
console.log(window.setSomething); // undefined
function scopeExample() {
var setSomething = 'something';
}
console.log(window.setSomething); // undefined
如果要保存全局变量,则需要将其设置在全局作用域(如window
)上。
// this will be set on a global-basis, however it will not affect the next request as
// explained in the next section
window.runOnce = 0;
function redirectPage() {
if (window.runOnce == 0 && windowWidth <= 767){
window.runOnce = 1;
window.location.assign("example.net/mobile-site");
}
else if (runOnce == 0 && windowWidth >= 767){
window.runOnce = 1;
window.location.assign("example.net/regular-site");
}
}
脚本生存期
想象一下,每个页面加载都是一个单独的应用程序。除非你愿意,否则它不知道以前的请求。你需要将其保存在cookie或客户端存储(如localStorage)中。
function redirectPage() {
var runOnce = localStorage.get('runOnce');
if (runOnce == '0' && windowWidth <= 767){
localStorage.set('runOnce', '1');
window.location.assign("example.net/mobile-site");
}
else if (runOnce == '0' && windowWidth >= 767){
localStorage.get('runOnce', '1');
window.location.assign("example.net/regular-site");
}
}
相关文章:
- 使用每500ms运行一次的jquery函数是个好主意吗
- For循环在Jquery中只运行一次
- 谷歌图表在运行应用程序时只能显示一次
- 使函数只运行一次(Javascript)
- 更改路由后,运行一次js脚本
- 只运行一次提取的脚本
- 可能只在for循环内部运行一次代码块
- 在单击事件中,第一次单击时激发代码一次,其余代码在所有单击时运行
- 在Flask中使用.getJSON请求时,只运行一次命令
- 运行“;非“;单击另一个函数中的函数仅一次
- JavaScript只有在最后一次被调用时才运行函数
- 数据互绑定问题:转换器只运行一次,无法绑定元素的 ID
- 您可以在节点.js上一次运行多个应用程序吗?
- 如何一次运行一次循环javascript
- 从命令行一次运行大量摩卡测试的好方法是什么
- 如何让 JavaScript 一次运行一个字符串
- 无法在一次运行中删除多个数组元素
- 如何使jquery函数一次运行一个
- 在一次运行中分配并返回一个变量
- 一次运行2个动画