jQuery Plugin Check Version

2020-02-10 02:18发布

When writing a new jQuery plugin is there a straightforward way of checking that the current version of jQuery is above a certain number? Displaying a warning or logging an error otherwise.

It would be nice to do something like:

jQuery.version >= 1.2.6

in some form or another.

15条回答
可以哭但决不认输i
2楼-- · 2020-02-10 03:02

Pass version as array of integers, like jQmin([1,4,2]) to check if the current version is equal or above v1.4.2.

function jQmin(min) {
    var i, cur, 
        cver = $.fn.jquery, 
        c = cver.split(".");
    while (min.length < c.length) min.push(0);

    for (i = 0; i < min.length; i++) {
        cur = parseInt(c[i]);
        if (cur > min[i]) return true;
        if (cur < min[i]) return false;
    }
    return (cver === min.join("."));
}
查看更多
Bombasti
3楼-- · 2020-02-10 03:05

Something like that?

It checks if jQuery is loaded, and if it is, checks the version. This method works correct for 2 digit version numbers too (1.10.28), and if needed you can extend it for 3 digits, if you replace the 100 numbers to 1000...

function checkJQueryMinVersion(need) {
    var v1 = need.split('.');
    var v1_num = 0;
    var v2 = jQuery.fn.jquery.split('.');
    var v2_num = 0;

    if(v1[0] != undefined) {
        v1_num += 100*100*parseInt(v1[0]);
    }
    if(v1[1] != undefined) {
        v1_num += 100*parseInt(v1[1]);
    }
    if(v1[2] != undefined) {
        v1_num += parseInt(v1[2]);
    }

    if(v2[0] != undefined) {
        v2_num += 100*100*parseInt(v2[0]);
    }
    if(v2[1] != undefined) {
        v2_num += 100*parseInt(v2[1]);
    }
    if(v2[2] != undefined) {
        v2_num += parseInt(v2[2]);
    }
    return (v1_num <= v2_num);
}
if(!window.jQuery || !checkJQueryMinVersion('1.10.28')) {
    alert('Loading //ajax.googleapis.com/ajax/libs/jquery/1.10.28/jquery.min.js');
    var script = document.createElement('script');script.type = 'text/javascript';
    script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.10.28/jquery.min.js';
    document.getElementsByTagName('head')[0].appendChild(script);
}
else {
    alert('Jquery version OK');
}
查看更多
何必那么认真
4楼-- · 2020-02-10 03:06
登录 后发表回答