重定向后运行一次函数

时间:2014-10-28 20:12:29

标签: javascript function redirect runonce

我正在尝试将访问网站的用户重定向到移动网站。这是我到目前为止所做的,但问题是每次页面加载时函数都会继续运行。页面加载后调用函数。我是一名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");
    }
}

1 个答案:

答案 0 :(得分:1)

您的方法存在一些问题。

范围

JavaScript有function scope。这意味着runOnce将永远是undefined函数之外的redirectPage。因此,每次通话都会runOnceundefined

&#13;
&#13;
console.log(window.setSomething); // undefined
function scopeExample() {
  var setSomething = 'something';
}
console.log(window.setSomething); // undefined
&#13;
&#13;
&#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");
    }
}