jQuery version compatibility detection

前端 未结 6 714
刺人心
刺人心 2020-12-09 13:38

Are there any resources that can test a jQuery script/extension/plugin/whatever for version compatibility issues?

6条回答
  •  佛祖请我去吃肉
    2020-12-09 13:58

    The code has some bugs, notably

    1. $.isVersion('1.9.2.17', '<', '2.0') returns false
    2. $.isVersion('1.17.2.1', '>', '1.8') returns false

    Solution
    1. is fixed by the attached code.
    2. is not as it's trickier without a complete re-write, and is a rarer case anyway.

    (function($) {
    /**
     * Used for version test cases.
     *
     * @param {string} left A string containing the version that will become
     *        the left hand operand.
     * @param {string} oper The comparison operator to test against. By
     *        default, the "==" operator will be used.
     * @param {string} right A string containing the version that will
     *        become the right hand operand. By default, the current jQuery
     *        version will be used.
     *
     * @return {boolean} Returns the evaluation of the expression, either
     *         true or false.
     */
    $.isVersion = function(left, oper, right) {
        if (left) {
            var pre = /pre/i,
                replace = /[^\d]+/g,
                oper = oper || "==",
                right = right || $().jquery,
                l = left.replace(replace, ''),
                r = right.replace(replace, ''),
                l_len = l.length, r_len = r.length,
                l_pre = pre.test(left), r_pre = pre.test(right);
    
            l = (r_len > l_len ? parseInt(l) * Math.pow(10, (r_len - l_len)) : parseInt(l));
            r = (l_len > r_len ? parseInt(r) * Math.pow(10, (l_len - r_len)) : parseInt(r));
    
            switch(oper) {
                case "==": {
                    return (true === (l == r && (l_pre == r_pre)));
                }
                case ">=": {
                    return (true === (l >= r && (!l_pre || l_pre == r_pre)));
                }
                case "<=": {
                    return (true === (l <= r && (!r_pre || r_pre == l_pre)));
                }
                case ">": {
                    return (true === (l > r || (l == r && r_pre)));
                }
                case "<": {
                    return (true === (l < r || (l == r && l_pre)));
                }
            }
        }
    
        return false;
    }
    })(jQuery);
    

提交回复
热议问题