2011-12-28 114 views
1

我正在開發一個函數,我想查看哪個useragent當前正在使用。
以下代碼僅僅是一個原型,它會返回首先讀取的任何值 - 在本例中爲IEJavaScript函數不返回正確的值

detectDevice = function() { 
    var userAgent = { 
     detect: function() { 
      return navigator.userAgent; 
     }, 
     detectBrowser: function() { 
      var browser = userAgent.detect(); 
      var currentBrowser; 
      return currentBrowser = browser.indexOf('IE') ? "Internet Explore" : browser.indexOf('Mozilla') ? "FireFox" : "UserAgent not recognized!"; 
     }, 
     version: function (identifier) { 
     } 
    }; 

    alert(userAgent.detectBrowser()); 
} 

我看不出有什麼問題。也許你們可以看到它並告訴我我在哪裏做錯了轉彎。

+2

你已經嘗試過使用'$ .browser'代替嗎?或者它不適合你的目的? – fcalderan 2011-12-28 09:34:47

+2

上面的代碼有什麼問題?此外,您可能會對http://api.jquery.com/jQuery.browser/感興趣 - 您可以查看jQuery源代碼以查看它們是如何實現的。 – Douglas 2011-12-28 09:37:49

回答

6

indexOf返回-1如果找不到匹配項。如果找到匹配項,返回的值就是找到的子串的字符索引。

要檢查串是否存在,你應該使用:

browser.indexOf('IE') != -1 
// If a match is found, a non-negative index is returned. So, this also works: 
//..... indexOf('IE') > -1 
// .... indexOf('IE') >= 0 
+0

做過這份工作。謝謝。幾分鐘,直到我可以接受:) – diceler 2011-12-28 09:39:30

2
return (browser.indexOf('IE') > -1) 
      ? "Internet Explorer" 
      : (browser.indexOf('Mozilla') > -1) 
       ? "FireFox" 
       : "UserAgent not recognized!"; 
+0

我不會upvote這個答案,因爲儘管是正確的,它並沒有描述爲什麼它的作品。 – Douglas 2011-12-28 09:43:28

0

你是不是檢查指數值...

,如果你找到的indexOf( 'IE' )> = 0應該是你的線...