深入学习jquery源码之扩展jquery与二次开发

深入学习jquery源码之jquery二次开发

jquery.js的设计与实现

(function (global, factory) {

    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = global.document ?
            factory(global, true) :
            function (w) {
                if (!w.document) {
                    throw new Error("jQuery requires a window with a document");
                }
                return factory(w);
            };
    } else {
        factory(global);
    }

}(typeof window !== "undefined" ? window : this, function (window, noGlobal) {

    var deletedIds = [];

    var slice = deletedIds.slice;

    var concat = deletedIds.concat;

    var push = deletedIds.push;

    var indexOf = deletedIds.indexOf;

    var class2type = {};

    var toString = class2type.toString;

    var hasOwn = class2type.hasOwnProperty;

    var support = {};

    var
        version = "1.11.3",

        // Define a local copy of jQuery
        jQuery = function (selector, context) {
            // The jQuery object is actually just the init constructor 'enhanced'
            // Need init if jQuery is called (just allow error to be thrown if not included)
            return new jQuery.fn.init(selector, context);
        },

        // Support: Android<4.1, IE<9
        // Make sure we trim BOM and NBSP
        rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

        // Matches dashed string for camelizing
        rmsPrefix = /^-ms-/,
        rdashAlpha = /-([\da-z])/gi,

        // Used by jQuery.camelCase as callback to replace()
        fcamelCase = function (all, letter) {
            return letter.toUpperCase();
        };

    jQuery.fn = jQuery.prototype = {
        // The current version of jQuery being used
        jquery: version,

        constructor: jQuery,

        // Start with an empty selector
        selector: "",

        // The default length of a jQuery object is 0
        length: 0,

        toArray: function () {
            return slice.call(this);
        }
       // For internal use only.
        // Behaves like an Array's method, not like a jQuery method.
        push: push,
        sort: deletedIds.sort,
        splice: deletedIds.splice
    };

    jQuery.extend = jQuery.fn.extend = function () {
        var src, copyIsArray, copy, name, options, clone,
            target = arguments[0] || {},
            i = 1,
            length = arguments.length,
            deep = false;

        // Handle a deep copy situation
        if (typeof target === "boolean") {
            deep = target;

            // skip the boolean and the target
            target = arguments[i] || {};
            i++;
        }

        // Handle case when target is a string or something (possible in deep copy)
        if (typeof target !== "object" && !jQuery.isFunction(target)) {
            target = {};
        }

        // extend jQuery itself if only one argument is passed
        if (i === length) {
            target = this;
            i--;
        }

        for (; i < length; i++) {
            // Only deal with non-null/undefined values
            if ((options = arguments[i]) != null) {
                // Extend the base object
                for (name in options) {
                    src = target[name];
                    copy = options[name];

                    // Prevent never-ending loop
                    if (target === copy) {
                        continue;
                    }

                    // Recurse if we're merging plain objects or arrays
                    if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) {
                        if (copyIsArray) {
                            copyIsArray = false;
                            clone = src && jQuery.isArray(src) ? src : [];

                        } else {
                            clone = src && jQuery.isPlainObject(src) ? src : {};
                        }

                        // Never move original objects, clone them
                        target[name] = jQuery.extend(deep, clone, copy);

                        // Don't bring in undefined values
                    } else if (copy !== undefined) {
                        target[name] = copy;
                    }
                }
            }
        }

        // Return the modified object
        return target;
    };


    jQuery.extend({
        // Unique for each copy of jQuery on the page
        expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""),

        // Assume jQuery is ready without the ready module
        isReady: true,

        error: function (msg) {
            throw new Error(msg);
        },
        isWindow: function (obj) {
            /* jshint eqeqeq: false */
            return obj != null && obj == obj.window;
        },
        // Support: Android<4.1, IE<9
        trim: function (text) {
            return text == null ?
                "" :
                (text + "").replace(rtrim, "");
        },
        // jQuery.support is not used in Core but other projects attach their
        // properties to it so it needs to exist.
        support: support
 });

    // Populate the class2type map
    jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (i, name) {
        class2type["[object " + name + "]"] = name.toLowerCase();
    });


    var Sizzle =
        /*!
         * Sizzle CSS Selector Engine v2.2.0-pre
         * http://sizzlejs.com/
         *
         * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
         * Released under the MIT license
         * http://jquery.org/license
         *
         * Date: 2014-12-16
         */
        (function (window) {


            // Optimize for push.apply( _, NodeList )
            try {
                push.apply(
                    (arr = slice.call(preferredDoc.childNodes)),
                    preferredDoc.childNodes
                );
                // Support: Android<4.0
                // Detect silently failing push.apply
                arr[preferredDoc.childNodes.length].nodeType;
            } catch (e) {
                push = {
                    apply: arr.length ?

                        // Leverage slice if possible
                        function (target, els) {
                            push_native.apply(target, slice.call(els));
                        } :

                        // Support: IE<9
                        // Otherwise append directly
                        function (target, els) {
                            var j = target.length,
                                i = 0;
                            // Can't trust NodeList.length
                            while ((target[j++] = els[i++])) { }
                            target.length = j - 1;
                        }
                };
            }
    })(window);

    function Sizzle(selector, context, results, seed) {
    // All others
    return select(selector.replace(rtrim, "$1"), context, results, seed);
    }

    jQuery.find = Sizzle;
    jQuery.expr = Sizzle.selectors;
    jQuery.expr[":"] = jQuery.expr.pseudos;
    jQuery.unique = Sizzle.uniqueSort;
    jQuery.text = Sizzle.getText;
    jQuery.isXMLDoc = Sizzle.isXML;
    jQuery.contains = Sizzle.contains;

   support = Sizzle.support = {};
   // Support: IE<8
   // Verify that getAttribute really returns attributes and not properties
   // (excepting IE8 booleans)
   support.attributes = assert(function (div) {
       div.className = "i";
       return !div.getAttribute("className");
   });
   Sizzle.error = function (msg) {
      throw new Error("Syntax error, unrecognized expression: " + msg);
   };


    // Implement the identical functionality for filter and not
    function winnow(elements, qualifier, not) {
        if (jQuery.isFunction(qualifier)) {
            return jQuery.grep(elements, function (elem, i) {
                /* jshint -W018 */
                return !!qualifier.call(elem, i, elem) !== not;
            });

        }

        if (qualifier.nodeType) {
            return jQuery.grep(elements, function (elem) {
                return (elem === qualifier) !== not;
            });

        }

        if (typeof qualifier === "string") {
            if (risSimple.test(qualifier)) {
                return jQuery.filter(qualifier, elements, not);
            }

            qualifier = jQuery.filter(qualifier, elements);
        }

        return jQuery.grep(elements, function (elem) {
            return (jQuery.inArray(elem, qualifier) >= 0) !== not;
        });
    }

    jQuery.filter = function (expr, elems, not) {
        var elem = elems[0];

        if (not) {
            expr = ":not(" + expr + ")";
        }

        return elems.length === 1 && elem.nodeType === 1 ?
            jQuery.find.matchesSelector(elem, expr) ? [elem] : [] :
            jQuery.find.matches(expr, jQuery.grep(elems, function (elem) {
                return elem.nodeType === 1;
            }));
    };

 jQuery.fn.extend({
        filter: function (selector) {
            return this.pushStack(winnow(this, selector || [], false));
        }
 });


    // A central reference to the root jQuery(document)
    var rootjQuery,

        // Use the correct document accordingly with window argument (sandbox)
        document = window.document,

        // A simple way to check for HTML strings
        // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
        // Strict HTML recognition (#11290: must start with <)
        rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,

        init = jQuery.fn.init = function (selector, context) {
            var match, elem;

            // HANDLE: $(""), $(null), $(undefined), $(false)
            if (!selector) {
                return this;
            }
            return jQuery.makeArray(selector, this);
        };

    // Give the init function the jQuery prototype for later instantiation
    init.prototype = jQuery.fn;

    // Initialize central reference
    rootjQuery = jQuery(document);


    jQuery.extend({

        sibling: function (n, elem) {
            var r = [];

            for (; n; n = n.nextSibling) {
                if (n.nodeType === 1 && n !== elem) {
                    r.push(n);
                }
            }

            return r;
        }
    });

    jQuery.fn.extend({
        has: function (target) {
            var i,
                targets = jQuery(target, this),
                len = targets.length;

            return this.filter(function () {
                for (i = 0; i < len; i++) {
                    if (jQuery.contains(this, targets[i])) {
                        return true;
                    }
                }
            });
        }
 });

    function sibling(cur, dir) {
        do {
            cur = cur[dir];
        } while (cur && cur.nodeType !== 1);

        return cur;
    }
   
   jQuery.each({
        next: function (elem) {
            return sibling(elem, "nextSibling");
        },
        prev: function (elem) {
            return sibling(elem, "previousSibling");
        }
        siblings: function (elem) {
            return jQuery.sibling((elem.parentNode || {}).firstChild, elem);
        },
        children: function (elem) {
            return jQuery.sibling(elem.firstChild);
        }
      }, function (name, fn) {
        jQuery.fn[name] = function (until, selector) {
            var ret = jQuery.map(this, fn, until);

            if (name.slice(-5) !== "Until") {
                selector = until;
            }

            if (selector && typeof selector === "string") {
                ret = jQuery.filter(selector, ret);
            }

            if (this.length > 1) {
                // Remove duplicates
                if (!guaranteedUnique[name]) {
                    ret = jQuery.unique(ret);
                }

                // Reverse order for parents* and prev-derivatives
                if (rparentsprev.test(name)) {
                    ret = ret.reverse();
                }
            }

            return this.pushStack(ret);
        };
    });


    (function () {
        var div = document.createElement("div");

        // Execute the test only if not already executed in another module.
        if (support.deleteExpando == null) {
            // Support: IE<9
            support.deleteExpando = true;
            try {
                delete div.test;
            } catch (e) {
                support.deleteExpando = false;
            }
        }

        // Null elements to avoid leaks in IE.
        div = null;
    })();

    /*
     * Helper functions for managing events -- not part of the public interface.
     * Props to Dean Edwards' addEvent library for many of the ideas.
     */
    jQuery.event = {

        global: {},

        trigger: function (event, data, elem, onlyHandlers) {
            var handle, ontype, cur,
                bubbleType, special, tmp, i,
                eventPath = [elem || document],
                type = hasOwn.call(event, "type") ? event.type : event,
                namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];

            cur = tmp = elem = elem || document;

            // Don't do events on text and comment nodes
            if (elem.nodeType === 3 || elem.nodeType === 8) {
                return;
            }

            // focus/blur morphs to focusin/out; ensure we're not firing them right now
            if (rfocusMorph.test(type + jQuery.event.triggered)) {
                return;
            }

            if (type.indexOf(".") >= 0) {
                // Namespaced trigger; create a regexp to match event type in handle()
                namespaces = type.split(".");
                type = namespaces.shift();
                namespaces.sort();
            }
            ontype = type.indexOf(":") < 0 && "on" + type;

            // Caller can pass in a jQuery.Event object, Object, or just an event type string
            event = event[jQuery.expando] ?
                event :
                new jQuery.Event(type, typeof event === "object" && event);

            // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
            event.isTrigger = onlyHandlers ? 2 : 3;
            event.namespace = namespaces.join(".");
            event.namespace_re = event.namespace ?
                new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") :
                null;

            // Clean up the event in case it is being reused
            event.result = undefined;
            if (!event.target) {
                event.target = elem;
            }

            // Clone any incoming data and prepend the event, creating the handler arg list
            data = data == null ?
                [event] :
                jQuery.makeArray(data, [event]);

            // Allow special events to draw outside the lines
            special = jQuery.event.special[type] || {};
            if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
                return;
            }

            // Determine event propagation path in advance, per W3C events spec (#9951)
            // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
            if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {

                bubbleType = special.delegateType || type;
                if (!rfocusMorph.test(bubbleType + type)) {
                    cur = cur.parentNode;
                }
                for (; cur; cur = cur.parentNode) {
                    eventPath.push(cur);
                    tmp = cur;
                }

                // Only add window if we got to document (e.g., not plain obj or detached DOM)
                if (tmp === (elem.ownerDocument || document)) {
                    eventPath.push(tmp.defaultView || tmp.parentWindow || window);
                }
            }

            // Fire handlers on the event path
            i = 0;
            while ((cur = eventPath[i++]) && !event.isPropagationStopped()) {

                event.type = i > 1 ?
                    bubbleType :
                    special.bindType || type;

                // jQuery handler
                handle = (jQuery._data(cur, "events") || {})[event.type] && jQuery._data(cur, "handle");
                if (handle) {
                    handle.apply(cur, data);
                }

                // Native handler
                handle = ontype && cur[ontype];
                if (handle && handle.apply && jQuery.acceptData(cur)) {
                    event.result = handle.apply(cur, data);
                    if (event.result === false) {
                        event.preventDefault();
                    }
                }
            }
            event.type = type;

            // If nobody prevented the default action, do it now
            if (!onlyHandlers && !event.isDefaultPrevented()) {

                if ((!special._default || special._default.apply(eventPath.pop(), data) === false) &&
                    jQuery.acceptData(elem)) {

                    // Call a native DOM method on the target with the same name name as the event.
                    // Can't use an .isFunction() check here because IE6/7 fails that test.
                    // Don't do default actions on window, that's where global variables be (#6170)
                    if (ontype && elem[type] && !jQuery.isWindow(elem)) {

                        // Don't re-trigger an onFOO event when we call its FOO() method
                        tmp = elem[ontype];

                        if (tmp) {
                            elem[ontype] = null;
                        }

                        // Prevent re-triggering of the same event, since we already bubbled it above
                        jQuery.event.triggered = type;
                        try {
                            elem[type]();
                        } catch (e) {
                            // IE<9 dies on focus/blur to hidden element (#1486,#12518)
                            // only reproducible on winXP IE8 native, not IE9 in IE8 mode
                        }
                        jQuery.event.triggered = undefined;

                        if (tmp) {
                            elem[ontype] = tmp;
                        }
                    }
                }
            }

            return event.result;
        },click: {
                // For checkbox, fire native event so checked state will be right
                trigger: function () {
                    if (jQuery.nodeName(this, "input") && this.type === "checkbox" && this.click) {
                        this.click();
                        return false;
                    }
                },

                // For cross-browser consistency, don't fire native .click() on links
                _default: function (event) {
                    return jQuery.nodeName(event.target, "a");
                }
            }
}


    jQuery.Event = function (src, props) {
        // Allow instantiation without the 'new' keyword
        if (!(this instanceof jQuery.Event)) {
            return new jQuery.Event(src, props);
        }

        // Event object
        if (src && src.type) {
            this.originalEvent = src;
            this.type = src.type;

            // Events bubbling up the document may have been marked as prevented
            // by a handler lower down the tree; reflect the correct value.
            this.isDefaultPrevented = src.defaultPrevented ||
                src.defaultPrevented === undefined &&
                // Support: IE < 9, Android < 4.0
                src.returnValue === false ?
                returnTrue :
                returnFalse;

            // Event type
        } else {
            this.type = src;
        }

        // Put explicitly provided properties onto the event object
        if (props) {
            jQuery.extend(this, props);
        }

        // Create a timestamp if incoming event doesn't have one
        this.timeStamp = src && src.timeStamp || jQuery.now();

        // Mark it as fixed
        this[jQuery.expando] = true;
    };

    // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
    // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
    jQuery.Event.prototype = {
        isDefaultPrevented: returnFalse,
        isPropagationStopped: returnFalse,
        isImmediatePropagationStopped: returnFalse,

        preventDefault: function () {
            var e = this.originalEvent;

            this.isDefaultPrevented = returnTrue;
            if (!e) {
                return;
            }

            // If preventDefault exists, run it on the original event
            if (e.preventDefault) {
                e.preventDefault();

                // Support: IE
                // Otherwise set the returnValue property of the original event to false
            } else {
                e.returnValue = false;
            }
        },
        stopPropagation: function () {
            var e = this.originalEvent;

            this.isPropagationStopped = returnTrue;
            if (!e) {
                return;
            }
            // If stopPropagation exists, run it on the original event
            if (e.stopPropagation) {
                e.stopPropagation();
            }

            // Support: IE
            // Set the cancelBubble property of the original event to true
            e.cancelBubble = true;
        },
        stopImmediatePropagation: function () {
            var e = this.originalEvent;

            this.isImmediatePropagationStopped = returnTrue;

            if (e && e.stopImmediatePropagation) {
                e.stopImmediatePropagation();
            }

            this.stopPropagation();
        }
    };

    // Create mouseenter/leave events using mouseover/out and event-time checks
    jQuery.each({
        mouseenter: "mouseover",
        mouseleave: "mouseout",
        pointerenter: "pointerover",
        pointerleave: "pointerout"
    }, function (orig, fix) {
        jQuery.event.special[orig] = {
            delegateType: fix,
            bindType: fix,

            handle: function (event) {
                var ret,
                    target = this,
                    related = event.relatedTarget,
                    handleObj = event.handleObj;

                // For mousenter/leave call the handler if related is outside the target.
                // NB: No relatedTarget if the mouse left/entered the browser window
                if (!related || (related !== target && !jQuery.contains(target, related))) {
                    event.type = handleObj.origType;
                    ret = handleObj.handler.apply(this, arguments);
                    event.type = fix;
                }
                return ret;
            }
        };
    });



    jQuery.noConflict = function (deep) {
        if (window.$ === jQuery) {
            window.$ = _$;
        }

        if (deep && window.jQuery === jQuery) {
            window.jQuery = _jQuery;
        }

        return jQuery;
    };

    // Expose jQuery and $ identifiers, even in
    // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
    // and CommonJS for browser emulators (#13566)
    if (typeof noGlobal === strundefined) {
        window.jQuery = window.$ = jQuery;
    }




    return jQuery;

}));

jquery的扩展与实现

(function (window, $, undefined) {
 var COOKIE_USER = "COOKIE_USER",
 SERVICE_ROOT = "http://localhost:8000/",
SERVICE_PATH = SERVICE_ROOT + "/"
 $.support.cors = true;
    var jqueryAjax = $.ajax;
    var _Core = function () {
        var eventarr = [];
        var _OnPageLoad = undefined;
        ///获取USER信息
        var getUser = function () {
            //var obj = {};
            //obj.USERID = $.cookie(COOKIE_USER);
            var cookieData = $.cookie(COOKIE_USER);
            if (cookieData === undefined) {
                $Core.TimeOut();
                return {};
            }
            var cookieuser;
            try {
                cookieuser = $.parseJSON(cookieData);
            } catch (e) {
                $Core.TimeOut();
                //window.location.href = TIMEOUT_PATH;
                return {};
            }

            if (cookieuser == undefined || cookieuser.USERID == undefined) {
                //每一登录信息跳转至登录页面
                //alert("登录超时!");
                $Core.TimeOut();
                //window.location.href = TIMEOUT_PATH;
                return {};
            }
            return cookieuser;

        }

        this.DEBUG = function () { return DEBUG; };
        //对外访问
        this.USER = function () {
            return getUser();
        };
        //服务地址
        this.SERVICEPATH = function () {
            return SERVICE_PATH;
        };
        this.SERVICEROOT = function () {
            return SERVICE_ROOT;
        }
        this.APPID = APP_ID;
        this.ajax = jqueryAjax;
        this.IsAjaxTimeOut = false;
        var _loading = function () {
            this.AjaxLoadingStart = function () {
                $("#pageloadingright").fadeIn();
            };

            this.HideAjaxLoading = function () {
                $("#pageloadingright").fadeOut(500);
            };

            this.HidePageLoading = function () {
                $("#pageloading").fadeOut(500);
            }

            this.HideAll = function () {
                this.HideAjaxLoading();
                this.HidePageLoading();
            }

        };
        this.Loading = new _loading();
        /**
         * 页面所有ajax加在完毕后执行
         * @param {function()} func 回调函数
         */
        this.OnPageLoad = function (func) {
            if (func !== undefined)
                _OnPageLoad = func;
        };

        var pageLoad = function () {
            if (_OnPageLoad)
                _OnPageLoad();
        };
        $(function () {
            var _interval = setInterval(function () {
                //if
                if (!window.ajaxruning) {
                    clearInterval(_interval);
                    pageLoad();
                }
            }, 100);

        });
    };
    window.$Core = new _Core();


    var _UI = function () {
        var _message = function () {
            var createAlert = function (type, msg, timeout) {
                if (timeout === undefined)
                    timeout = 2000;

                var div = $(
                    '<div class="cntenalert" >' +
                    '<div class="alert-icons"></div>' +
                    '<div class="alert-close">×</div>' +
                    '<div class="alert-msg"></div></div>');
                var winWidth = ($(window).width() - 200) / 2;
                div.css("left", winWidth);
                div.addClass(type);

                var close = div.find(".alert-close");
                var divmsg = div.find(".alert-msg");
                close.click(function () {
                    div.fadeOut(function () {
                        div.remove();
                    });
                });

                divmsg.text(msg);

                div.fadeIn(function () {

                });

                $("body").append(div);
                if (timeout > 0)
                    setTimeout(function () {
                        div.fadeOut(function () {
                            div.remove();
                        });
                    }, timeout);

            }
            /**
             * 成功提示
             * @param {any} msg
             */
            this.success = function (msg) {
                createAlert("alert", msg);
            }
            /**
             * 错误的提示
             * @param {any} msg
             */
            this.error = function (msg) {
                createAlert("alert-error", msg, 5000);
            }
            /**
             * 提醒
             * @param {any} msg
             */
            this.warning = function (msg) {
                createAlert("alert-warning", msg, 3000);
            }
            /**
             * 清除所有提示信息
             * */
            this.clear = function () {
                $(".cntenalert").fadeOut(function () {
                    $(".cntenalert").remove();
                });
            }

        }
        this.message = new _message();
        /**
         * 打开一个url 的Dialog 对话框
         * @param {any} id 指定一个名字
         * @param {any} url 页面地址
         * @param {any} options Dialog 参数
         */
        this.openDialog = function (id, url, options) {
            var frameid = id + "_frame";
            var win = $("#" + id);
            if (url.indexOf("?") > -1)
                url = url + "&_r=" + Math.random();
            else
                url = url + "?_r=" + Math.random();
            var getframe = function (id, url) {
                var f = $('<iframe id="{0}" src="{1}" width="100%" height="100%" scrolling="no" frameborder="0" ></iframe>'.format(id, url));
                return f;
            };

            if (win.size() == 0) {
                var $frame = getframe(frameid, url);
                //$frame.height(options.height - 43);
                var defaultOptions = {
                    maximizable: true,
                    resizable: true,
                    closed: false,
                    cache: false,
                    modal: true,
                    constrain: true,
                    width: "80%",
                    height: "90%"
                };
                if (options) {
                    $.extend(defaultOptions, options,
                        {
                            onClose: function () {
                                win.remove();
                                if ($.isFunction(options.onClose)) {
                                    options.onClose.apply(this);
                                }
                            }
                        });
                }
                defaultOptions.content = $frame;

                var dd = $("<div id='" + id + "' style='overflow:hidden' />");
                return dd.dialog(defaultOptions);
            } else {
                $("#" + frameid).attr("src", url);
                return win.dialog("open");
            }

        }
    };
    $Core.UI = new _UI();

})(window, jQuery);
(function (window, $) {


    /**统一处置ajax 的一些事件 和参数*/
    function _ajaxSetup() {

        $(document).ajaxStart(function () {
            window.ajaxruning = true;
            $Core.IsAjaxTimeOut = false;
            $Core.Loading.AjaxLoadingStart();
            //console.log("documentStart");
        }).ajaxStop(function () {
            window.ajaxruning = false;
            $Core.Loading.HideAjaxLoading();
            //console.log("documentStop");

        }).ajaxError(function (event, XMLHttpRequest, ajaxOptions, thrownError) {
            $Core.Loading.HideAll();
            if (thrownError === "timeout") {
                $Core.IsAjaxTimeOut = true;
                showError(ajaxOptions, "timeout", "请求超时,请检查您的网络连接!");
                return;
            }
            showError(ajaxOptions, XMLHttpRequest.status, XMLHttpRequest.responseText);
        });

        //这里设置统一的头信息
        $.ajaxSetup({
            beforeSend: function (xhr) {
                //alert(this.url);
                if (this.url) {
                    if (!this.url.contains("http"))
                        this.url = $Core.SERVICEPATH() + this.url;
                }
            },
            //dataType: "josn",
            headers: {
                'token': $Core.USER().TOKEN,
                'appid': $Core.APPID
            },
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            timeout: $Core.Config.ajaxTimeout,
            cache: false,
            //xhrFields: {
            //    withCredentials: true
            //},
            //dataType:"json",
            crossDomain: true,
            complete: function (XHR, TS) {
                if (TS === "success") {
                    var result = XHR.responseJSON;
                    if (result && result.code != undefined) {
                        if (result.code == "500") {
                            showError(this, 500, result.msg);
                            return false;
                        }
                        else if (result.code == "401") { //登录信息失败
                            showError(this, 401, "您的登录信息已经失效,请重新登录系统!", $Core.TimeOut);
                            return false;
                        }
                        else if (result.code == "403") { //资源信息失败
                            return false;
                        }
                    }
                }
                //console.log(XHR, TS);
            }

        });
    }


    /*************************************ajaxEnd***************************************/
    _ajaxSetup();

})(window, jQuery);


//禁止表单回车自动提交
$(function () {
    $("form input").keydown(function () {
        if (event.keyCode == 13) { return false };
    });
});

jquery的二次开发设计与实现

(function (window, $, undefined) {

    var version = "2014-04-24",

        //  定义 字符串对象(String) 扩展对象基元
        coreString = function () { return String.apply(this, arguments); },

        //  定义 日期对象(Date) 扩展对象基元
        coreDate = function () { return Date.apply(this, arguments); },

        //  定义 数值对象(Number) 扩展对象基元
        coreNumber = function () { return Number.apply(this, arguments); },

        //  定义 数组对象(Array) 扩展对象基元
        coreArray = function () { return Array.apply(this, arguments); },

        //  定义 布尔值对象(Boolean) 扩展对象基元
        coreBoolean = function () { return Boolean.apply(this, arguments); },

        //  定义 通用工具方法 扩展对象基元
        coreUtil = function () { return Object.apply(this, arguments); },
        //  定义 空值 集合基元
        coreNullable = {},

        //  定义 jQuery 扩展对象基元
        coreJquery = function () { return $.apply(this, arguments); },

        //  定义 HTML5 工具组件对象基元
        coreHtml5 = {};


    coreString.fn = coreString.prototype = {};
    coreDate.fn = coreDate.prototype = {};
    coreNumber.fn = coreNumber.prototype = {};
    coreArray.fn = coreArray.prototype = {};
    coreBoolean.fn = coreBoolean.prototype = {};
    coreUtil.fn = coreUtil.prototype = {};
    coreJquery.fn = coreJquery.prototype = {};

    coreNullable.String = new String();
    coreNullable.Date = new Date();
    coreNullable.Number = new Number();
    coreNullable.Array = [];
    coreNullable.Boolean = new Boolean();
    coreNullable.Function = new Function();
    coreNullable.Object = new Object();

    coreJquery.string = coreString;
    coreJquery.date = coreDate;
    coreJquery.number = coreNumber;
    coreJquery.array = coreArray;
    coreJquery.boolean = coreBoolean;
    coreJquery.util = coreUtil;
    coreJquery.nullable = coreNullable;
    coreJquery.html5 = coreHtml5;


    var document = coreUtil.document = window.document,
        location = coreUtil.location = window.location,
        docElem = coreUtil.docElem = document.documentElement,
        history = coreUtil.history = window.history,
        parent = coreUtil.parent = window.parent,
        top = coreUtil.top = window.top,
        $$ = coreJquery.emptyJquery = coreJquery.empty$ = coreJquery.$$ = coreUtil.emptyJquery = coreUtil.empty$ = coreUtil.$$ = $(),
        core_string = version,
        //core_date = coreNullable.Date,
        //core_number = coreNullable.Number,
        core_array = coreNullable.Array,
        //core_boolean = coreNullable.Boolean,
        //core_trim = core_string.trim,
        core_push = core_array.push,
        core_slice = core_array.slice,
        core_splice = core_array.splice,
        //core_sort = core_array.sort,
        //core_join = core_array.join,
        core_isArray = Array.isArray;


    //  定义版本
    coreUtil.version = version;

    //  测试对象是否是窗口(有可能是Frame)。
    coreUtil.isWindow = $.isWindow;

    //  测试传入的参数是否是一个 javscript 对象;
    coreUtil.isObject = function (obj) { return coreUtil.type(obj) == "object"; };

    //  测试对象是否是数组(Array)。
    coreUtil.isArray = $.isArray;

   //  测试对象是否是函数。
    //  注意:在IE浏览器里,浏览器提供的函数比如'alert'还有 DOM 元素的方法比如 'getAttribute' 将不认为是函数。
    coreUtil.isFunction = $.isFunction;

    //  判断传入的字符串是否为Null或者为空字符串或者全是空格。
    coreUtil.trim = $.trim;


    //  获取当前页面 url 参数。
    //  返回值:该方法返回一个数组,数组中的每个元素都是一个 JSON 对象,该 JSON 对象包含如下属性:
    //      name:   表示 url 参数的名称;
    //      value:  表示 url 参数的值;
    //  也可以通过数组访问器快速访问某个特定名称的参数值,方法如:coreUtil.getRequest()["id"]。
    coreUtil.getRequest = function () {
        var search = location.search;
        if (search.substr(0, 1) == "?") { search = search.substr(1, search.length - 1); }
        var result = [];
        if (search.length > 0) {
            var params = search.split("&");
            for (var i = 0; i < params.length; i++) {
                var param = params[i];
                var pos = param.indexOf("=");
                var name = param.substring(0, pos);
                var value = param.substr(pos + 1);
                result.push({ name: name, value: value });
                result[name] = value;
            }
        }
        return result;
    };
    coreUtil.request = coreUtil.getRequest();

    /////////////////////////////////////////////////////////////////////////////////////////////// 
    //  javascript 字符(串)函数功能扩充
    /////////////////////////////////////////////////////////////////////////////////////////////// 

    //  判断传入的对象是否是一个字符串。
    coreString.isString = coreUtil.isString;

    //  判断传入的字符串是否为Null或者为空字符串。
    coreString.isNullOrEmpty = function (str) { return str === undefined || str === null || str === ""; };
    coreString.prototype.isNullOrEmpty = function () { return coreString.isNullOrEmpty(this); };

    //  判断传入的字符串是否为Null或者为空字符串或者全是空格。
    coreString.isNullOrWhiteSpace = function (str) { return coreString.isNullOrEmpty(str) || coreString.trim(String(str)) === ""; };
    coreString.prototype.isNullOrWhiteSpace = function () { return coreString.isNullOrWhiteSpace(this); };

    //  判断传入的字符串是否为 HTML 代码段。
    coreString.isHtmlText = function (str) {
        str = coreString.isNullOrEmpty(str) ? "" : String(str);
        return str.length >= 3 && str.charAt(0) === "<" && str.charAt(str.length - 1) === ">";
    };
    coreString.prototype.isHtmlText = function () { return coreString.isHtmlText(this); };

    //  用新字符串替换与给定字符串匹配的所有子串;该方法将返回源字符串处理后的一个副本,而不会改变源字符串的值。
    coreString.replaceAll = function (str, substr, replacement, ignoreCase) {
        if (!substr || substr == replacement) { return str; }
        //var regexp = coreUtil.isRegExp(substr) ? substr : new RegExp(String(substr), ignoreCase ? "gm" : "igm");
        //return str.replace(regexp, replacement);
        str = coreString.isNullOrEmpty(str) ? "" : String(str);
        var length = str.length, i = 0;
        while (str.indexOf(substr) > -1 && i++ < length) { str = str.replace(substr, replacement); }
        return str;
    };
    coreString.prototype.replaceAll = function (substr, replacement) { return coreString.replaceAll(this, substr, replacement); };

    //  去除字符串左边的空格;该方法将返回源字符串处理后的一个副本,而不会改变源字符串的值。
    coreString.ltrim = function (str) {
        str = coreString.isNullOrEmpty(str) ? "" : String(str);
        return str.replace(/(^\s*)/g, "");
    };
    coreString.prototype.ltrim = function () { return coreString.ltrim(this); };

    //  去除字符串右边的空格;该方法将返回源字符串处理后的一个副本,而不会改变源字符串的值。
    coreString.rtrim = function () {
        str = coreString.isNullOrEmpty(str) ? "" : String(str);
        return str.replace(/(\s*$)/g, "");
    };
    coreString.prototype.rtrim = function () { return coreString.rtrim(this); };


})(window, jQuery);




                $Core.UI.openDialog("editwind", url + "&"+_self.listOption.idKey+"=" + rows[0][_self.listOption.idKey]+"&type=close",
                    {
                        title: "关闭",
                        width: '50%',
                        height: '90%',
                        onClose: function () {
                            $("#dglist").datagrid("load");
                        }
                    });


        var key = $.util.request[$id];
        var type = $.util.request["type"];

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/85207438