美文网首页
jquery的简单实现,jquery-me.js

jquery的简单实现,jquery-me.js

作者: tzujun | 来源:发表于2018-10-03 12:36 被阅读0次

完整代码

(function(global, factory) {

    typeof define === 'function' ? define(factory) : global.$ = factory();

})(this, function() {

    var jQuery = function(selector) {

        return new jQuery.fn.init(selector);

    }

    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

    jQuery.trim = function(text) {

        return text == null ? "" : (text + "").replace(rtrim, "");

    }

    jQuery.each = function(obj, callback) {

        var i, length = obj.length;

        for(i = 0; i < length; i++) {

            if(callback.call(obj[i], i) === false) break;

        }

        return obj;

    }

    jQuery.ajax = function(obj) {

        var ajax, k, response, isJSON = obj.dataType && 'JSON' == obj.dataType.toUpperCase();

        var url = 'string' == typeof obj.url ? obj.url : location.href;

        var isPOST, type = (isPOST = obj.type && 'POST' == obj.type.toUpperCase()) ? 'POST' : 'GET';

        var data = '';

        if('object' == typeof obj.data) {

            for(k in obj.data) {

                data = data + '&' + k + '=' + encodeURIComponent(obj.data[k]);

            }

            data = data.substring(1);

        } else if('srting' == typeof obj.data) {

            data = obj.data;

        }

        if(XMLHttpRequest) {

            ajax = new XMLHttpRequest();

        } else if(ActiveXObject) {

            ajax = new ActiveXObject("Microsoft.XMLHTTP");

        } else return;

        !isPOST && (url = url + '?' + data);

        ajax.open(type, url, false === obj.async ? false : true);

        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        ajax.send(isPOST ? data : null);

        ajax.onreadystatechange = function() {

            if(ajax.readyState == 4) {

                if(ajax.status == 200) {

                    response = jQuery.trim(ajax.responseText);

                    response = isJSON ? JSON.parse(response) : response;

                    obj.success && obj.success.call({}, response);

                } else {

                    obj.error && obj.error.call({}, ajax.status, ajax.statusText);

                }

            }

        }

    }

    jQuery.event = {

        add: function(elem, type, selector, fn) {

            elem.each(function() {

                if(this.addEventListener) {

                    this.addEventListener(type, eventDo(this));

                } else if(this.attachEvent) {

                    this.attachEvent('on' + type, eventDo(this));

                } else return;

            });

            function eventDo(docElem) {

                if(selector) {

                    return function() {

                        jQuery(docElem).find(selector).each(function() {

                            if(this === document.elementFromPoint(event.clientX, event.clientY)) {

                                'function' === typeof fn && fn.call(this);

                            }

                        });

                    }

                } else {

                    return function() {

                        'function' === typeof fn && fn.call(docElem);

                    }

                }

            }

        }

    };

    var textType = typeof document.textContent === 'undefined' ? 'innerText' : 'textContent';

    jQuery.fn = jQuery.prototype = {

        length: 0,

        init: function(selector) {

            this.length = 1;

            this[0] = document;

            if(!selector) {

                return this;

            } else if(typeof selector === 'string') {

                return this.find(selector);

            } else if(selector.nodeType) {

                this[0] = selector;

            }

            return this;

        },

        find: function(selector) {

            if(typeof selector != 'string') return this;

            var i, elems, elem = jQuery();

            delete elem[0];

            elem.length = 0;

            this.each(function() {

                elems = this.querySelectorAll(selector);

                for(i = 0; i < elems.length; i++) {

                    elem[elem.length] = elems[i];

                    elem.length++;

                }

            });

            return elem;

        },

        each: function(callback) {

            return jQuery.each(this, callback);

        },

        parent: function() {

            var elem = jQuery();

            delete elem[0];

            elem.length = 0;

            this.each(function(i) {

                elem[i] = this.parentNode;

                elem.length++;

            });

            return elem;

        },

        check: function() {

            var elem = jQuery();

            delete elem[0];

            elem.length = 0;

            this.each(function() {

                if(this.checked) {

                    elem[elem.length] = this;

                    elem.length++;

                }

            });

            return elem;

        },

        remove: function() {

            return this.each(function() {

                if(this && this.parentNode) {

                    this.parentNode.removeChild(this);

                }

            });

        },

        append: function(htmlstr) {

            return domManip(this, htmlstr, function(elem) {

                if(this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {

                    this.appendChild(elem);

                }

            });

        },

        prepend: function(htmlstr) {

            return domManip(this, htmlstr, function(elem) {

                if(this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {

                    this.insertBefore(elem, this.firstChild);

                }

            });

        },

        before: function(htmlstr) {

            return domManip(this, htmlstr, function(elem) {

                if(this.parentNode) {

                    this.parentNode.insertBefore(elem, this);

                }

            });

        },

        after: function(htmlstr) {

            return domManip(this, htmlstr, function(elem) {

                if(this.parentNode) {

                    this.parentNode.insertBefore(elem, this.nextSibling);

                }

            });

        },

        empty: function() {

            return this.each(function() {

                if(this.nodeType === 1) {

                    this[textType] = "";

                }

            });

        },

        text: function(value) {

            if(value === undefined) {

                return this[0] && this[0][textType] || '';

            } else {

                return this.empty().each(function() {

                    if(this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {

                        this[textType] = value;

                    }

                });

            }

        },

        html: function(value) {

            if(value === undefined) {

                return this[0] && this[0].innerHTML || '';

            } else {

                return this.empty().each(function() {

                    if(this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {

                        this.innerHTML = value;

                    }

                });

            }

        },

        val: function(value) {

            if(value === undefined) {

                return this[0] && this[0].value || '';

            } else {

                return this.empty().each(function() {

                    if(this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {

                        this.value = value;

                    }

                });

            }

        },

        on: function(type, selector, fn) {

            if(fn == undefined) {

                fn = selector;

                selector = undefined;

            }

            jQuery.event.add(this, type, selector, fn);

            return this;

        },

        css: function(name, value) {

            return this.each(function() {

                this.style[name] = value;

            });

        },

        addClass: function(className) {

            return this.each(function() {

                this.className = this.className + ' ' + className;

            });

        },

        removeClass: function(className) {

            return this.each(function() {

                this.className = this.className.replace(new RegExp(className, "g"), '').replace(/^\s+|\s+$/g, '');

            });

        },

        data: function(name, value) {

            if(value === undefined) {

                return this[0] && (this[0].dataset ? this[0].dataset[name] : this[0].getAttribute('data-' + name)) || '';

            } else {

                return this.each(function() {

                    if(this.dataset) {

                        this.dataset = value;

                    } else {

                        this.setAttribute('data-' + name, value);

                    }

                });

            }

        }

    }

    function domManip(collection, htmlstr, callback) {

        if(typeof htmlstr != 'string') return collection;

        var node, first, tmp, i, l = collection.length;

        var iNoClone = l - 1;

        if(l) {

            node = buildNode(htmlstr, collection[0].ownerDocument);

            first = node.firstChild;

            if(node.childNodes.length === 1) {

                node = first;

            }

            if(first) {

                for(i = 0; i < l; i++) {

                    if(i !== iNoClone) {

                        tmp = node.cloneNode(true);

                    } else {

                        tmp = node;

                    }

                    callback.call(collection[i], tmp);

                }

            }

        }

        return collection;

    }

    function buildNode(htmlstr, context) {

        var fragment = context.createDocumentFragment();

        var node = fragment.appendChild(context.createElement("div"));

        node.innerHTML = htmlstr;

        return node;

    }

    jQuery.fn.init.prototype = jQuery.fn;

    return jQuery;

});

相关文章

网友评论

      本文标题:jquery的简单实现,jquery-me.js

      本文链接:https://www.haomeiwen.com/subject/kdmzoftx.html