【发布时间】:2014-10-28 20:12:28
【问题描述】:
我正在尝试将访问网站的用户重定向到移动网站。这是我到目前为止所做的,但问题是每次页面加载时该函数都会继续运行。页面加载后调用这些函数。我是 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 在页面加载时运行,因为 javascript 在页面加载时按照它在页面上出现的顺序执行。当您更改 window.location 时,您正在加载一个不同的页面,并且该页面上的 javascript 将在页面加载时执行。
-
我做的是做一个饼干。如果 cookie 存在,则代码不运行,如果不存在(清除缓存或过期),则运行并创建一个新 cookie。
-
@user3757910 你想通过检查
Storage未定义来完成什么?如果您检查那里发生的事情,您可以找出问题的根源。
标签: javascript function redirect runonce