2013-08-16 36 views
3

我正在更新引用$ .browser.msie的舊項目。移動到jQuery 1.9當然打破了這一點。

如何重寫此代碼以獲得相同的布爾值而不必包含jQuery Migrate?

這段代碼被深埋在一個我們使用的舊javascript庫中,它需要確定msie是否正在運行,然後處理這些知識。我們寧願不要太過於編輯javascript,因爲它很脆弱。

+0

見這可能幫助:HTTP://stackoverflow.com/questions/14892095/browser-msie-error-after-update-to-jquery-1-9-1 – matpol

+3

使用功能檢測,但您需要知道是否需要測試哪些特定功能(如果有)。我不知道是否**所有**怪癖都可以檢測到,但是 –

+1

您使用它的目的是什麼? 「新方法」是使用功能檢測,以便您不會假設只有IE /非IE可以執行某些操作。在過去的IE瀏覽器中,IE10並不是那麼糟糕。 –

回答

8

你可以考慮包括jQuery的1.8(https://github.com/jquery/jquery/blob/1.8.3/src/deprecated.js相關的代碼:

(function() { 
    var matched, browser; 

    // Use of jQuery.browser is frowned upon. 
    // More details: http://api.jquery.com/jQuery.browser 
    // jQuery.uaMatch maintained for back-compat 
    jQuery.uaMatch = function(ua) { 
     ua = ua.toLowerCase(); 

     var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || 
      /(webkit)[ \/]([\w.]+)/.exec(ua) || 
      /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || 
      /(msie) ([\w.]+)/.exec(ua) || 
      ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || 
      []; 

     return { 
      browser: match[ 1 ] || "", 
      version: match[ 2 ] || "0" 
     }; 
    }; 

    matched = jQuery.uaMatch(navigator.userAgent); 
    browser = {}; 

    if (matched.browser) { 
     browser[ matched.browser ] = true; 
     browser.version = matched.version; 
    } 

    // Chrome is Webkit, but Webkit is also Safari. 
    if (browser.chrome) { 
     browser.webkit = true; 
    } else if (browser.webkit) { 
     browser.safari = true; 
    } 

    jQuery.browser = browser; 
})(); 
0

如果你確實需要這樣做。有一個哈克,醜陋和相當無痛的方式: 把這個到你的HTML。它會爲你設置$ .browser.msie。

檢測IE除了IE10:

<!--[if IE]> 
    <script type="text/javascript"> 
     $(function(){ 
      if(!$.browser && !$.browser.msie) { $.browser = {}; } 
      else { return; } 
      $.browser.msie = true; 
     }); 
    </script> 
<![endif]--> 


檢測所有IE包括IE10

<!--[if IE]> 
    <script type="text/javascript"> 
     $(function(){ 
      $('body').addClass('msie'); 
     }); 
    </script> 
<![endif]--> 
<script type="text/javascript"> 
    $(function(){ 
     var $body = $('body'); 
     // use this only if you need to detect IE10 
     if (Function('/*@cc_on return [email protected]*/')()){ 
      $body.addClass('msie'); 
     } 

     if($body.hasClass('msie')) { 
      if(!$.browser && !$.browser.msie) { $.browser = {}; } 
      else { return; } 
      $.browser.msie = true; 
     } 
    }); 
</script> 
+0

在IE10中不起作用。 – JJJ

+0

需要確保'$ .browser'在添加'msie'屬性前先存在 –

+0

它應該是'if($。browser){$。browser.msie = true;}' –