2011-08-26 22 views
0

我想在某些情況下獲得一個jQuery腳本重定向到我的網站的移動優化版本。基本上,如果瀏覽器是移動的,它將重定向到移動設備,除非在URL中獲得參數「mobile = 0」。我有一種方法來檢測它是否是移動的,並且我有一個插件可以讓你通過jQuery從URL獲取參數(http://www.mathias-bank.de/2007/04/21/jquery-plugin- geturlparam-version-2 /)的工作。jQuery重定向移動在某些情況下

我想要的流程是如果它是桌面,將移動變量設置爲0,而不是重定向。然後,如果它是移動的,則重定向,除非網址將移動變量設置爲0。

現在,如果我在移動瀏覽器上,它不會重定向。我測試了我的重定向在移動設備上工作,但添加了url參數後,它停止工作。

我開始編碼,但由於我在JavaScript上有點新,我知道我犯了一些錯誤。我的代碼到目前爲止是:

 var deviceAgent = navigator.userAgent.toLowerCase(); 
    var agentID = deviceAgent.match(/(iphone|ipod|ipad|android|iemobile|ppc|smartphone|blackberry|webos|)/); 
    var mobile = $.getURLParam("mobile"); 
    if (!agentID) { 
     mobile = "0"; 
    } 
    else { 
     return false; 
    } 
    if ($.getURLParam("mobile")==0) { 
      return false; 
    } 
else { 
    if (agentID) { 
     window.location.replace("http://remiwebo.vacau.com"); 
    } 
    else { 
     return false; 
    } 
} 

在此先感謝!

+0

那麼,到目前爲止你的代碼有什麼問題? –

+0

現在,如果我在移動瀏覽器上,它不會重定向。我測試了我的重定向在移動設備上工作,但添加了url參數後,它停止工作。編輯:意識到我忘了補充說。謝謝! – Remixz

+0

如果在添加$ .getURLParam(「mobile」)之後它停止工作,您是否測試了一下,看看您是否從該jQuery方法獲取了值? (一條警報消息就足夠了)。但看看你的邏輯,如果它不是一個移動設備,你永遠不能解析移動參數 –

回答

1

我認爲你的邏輯可能比它需要的複雜一點。

我想要的流程是如果它是桌面,請將移動變量設置爲 0,而不是重定向。然後,如果它是移動的,則重定向,除非移動 變量由url設置爲0。

1)如果它是手機 - 重定向。

2)如果它有移動= 0不重定向。

3)如果它是PC不重定向。

如何在您的計算機上測試移動版本? (手機= 1)?

var deviceAgent = navigator.userAgent.toLowerCase(); 
document.write("Device Agent: " + deviceAgent); 
var agentID = deviceAgent.match(/(iphone|ipod|ipad|android|iemobile|ppc|smartphone|blackberry|webos|)/); 

document.write("</br>Agent ID: " + agentID); 


//This doens't work well on JSfiddle, but it wwill work (non jquery way) 
var mobile = getUrlVars()["mobile"]; 
document.write("<br />Mobile : " + mobile); 

    //If we're a cell phone AND if there is no sign of the mobile parameter, or it is other than 0, redirect. 
    if (agentID.length > 3 && (!mobile || mobile != "0")) { 
     document.write("<br />GO GO GO TO MOBILE SITE"); 
     window.location = "mobile.verison.of.my.site.com" 
    } 
    else { 
     document.write("<br />DO NOT GO TO MOBILE"); 
     return false; 
    } 
     // Handler for .ready() called. 


function getUrlVars() 
{ 
    var vars = [], hash; 
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 
    for(var i = 0; i < hashes.length; i++) 
    { 
     hash = hashes[i].split('='); 
     vars.push(hash[0]); 
     vars[hash[0]] = hash[1]; 
    } 
    return vars; 
} 

更新:AGENTID會= 「」,如果它沒有找到在deviceAgent任何字符串2字符串。因此,而不是測試它是否爲空,您可以檢查它的長度。

http://jsfiddle.net/3zv64/

+0

該代碼的唯一問題是它在PC和移動設備上重定向。這將需要在PC上,手機自動設置爲0。 – Remixz

+0

謝謝!你的代碼有一個問題,就是(例如)我的iPod touch,我得到了「ipod,ipod」。所以,我將agentID.length> 3反轉爲agentID.length <3,它完美地工作!再次感謝你的幫助。 :-) – Remixz

相關問題