jQuery 1.9-如何从$.browser.msie迁移

jQuery 1.9 - How to migrate from $.browser.msie?

本文关键字:browser msie 迁移 jQuery      更新时间:2023-09-26

我正在更新一个引用$browser.msie的旧项目。转到jQuery 1.9当然会打破这一点。

如何在不必包含jQueryMigrate的情况下重写此代码以获得相同的布尔值?

代码深深地埋在我们使用的一个旧的javascript库中,该库需要确定msie是否正在运行,然后根据知识进行处理。我们宁愿不要过多地编辑javascript,因为它很脆弱。

您可以考虑包含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;
})();

jQuery.browser()方法自jQuery 1.3以来一直被弃用,并在1.9中被删除。如果需要,它可以作为jQueryMigrate插件的一部分提供。

另请参阅jQuery Core 1.9升级指南

如果您真的需要这样做。有一种粗鲁、丑陋、无痛的方式:把这个放到你的HTML中。它将为您设置$.browser.msie。

检测IE10以外的IE:

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


检测包括IE10在内的所有IE

<!--[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 document.documentMode===10@*/')()){
            $body.addClass('msie');
        }
        if($body.hasClass('msie')) {
            if(!$.browser && !$.browser.msie) { $.browser = {}; } 
            else { return; }
            $.browser.msie = true;
        }
    });
</script>