【问题标题】:How Do You Break A JavaScript Redirect To Mobile?你如何打破 JavaScript 重定向到移动设备?
【发布时间】:2014-02-04 00:15:05
【问题描述】:

我创建了一个简单的脚本来检测用户设备,如果该设备是移动设备,它将重定向到移动端。当您在移动设备上时,该网站将创建一个 cookie,当您再次访问桌面时,该 cookie 应该会破坏重定向。以下是主网站上的代码:

<script>
// simple mobile detection script
// create a variable to store response to user agent queries
var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() ||     isMobile.Opera() || isMobile.Windows());
    }
};

// if any of the listed agents are accessing the page, redirect to mobile version with     geolocation enabled
if(isMobile.any()) 
{
    if(jQuery.cookie('mobilea')!== 1)
    {
         window.location="/mobile/";
         console.log('true');
    }
}
</script>

在移动端成功实例化cookie,代码如下:

jQuery.cookie('mobilea',1, {path: '/'});

有什么想法吗?

【问题讨论】:

    标签: javascript jquery wordpress cookies


    【解决方案1】:

    if(jQuery.cookie('mobilea')!== 1) 将始终为 false,因为 '1' 不完全等于 1。要么切换到!=,要么将1替换为'1'

    if(jQuery.cookie('mobilea')!== '1')
    

    【讨论】:

      【解决方案2】:

      jQuery.cookie('mobilea') 将返回一个字符串而不是整数,因此您对它的严格检查永远不会是错误的。如果你把它改成

      jQuery.cookie('mobilea') !== '1'
      

      您可以正确测试它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-28
        • 1970-01-01
        • 2014-01-31
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        相关资源
        最近更新 更多