我正在尝试将访问网站的用户重定向到移动网站。这是我到目前为止所做的,但问题是每次页面加载时函数都会继续运行。页面加载后调用函数。我是一名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");
}
}
答案 0 :(得分:1)
您的方法存在一些问题。
JavaScript有function scope。这意味着runOnce将永远是undefined
函数之外的redirectPage
。因此,每次通话都会runOnce
为undefined
。
console.log(window.setSomething); // undefined
function scopeExample() {
var setSomething = 'something';
}
console.log(window.setSomething); // undefined
&#13;
如果要保存全局变量,则需要在全局范围内设置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");
}
}