学过jQuery快一年了,学jQuery时曾尝试封装过一个简易的jQuery,也是为了考察自己对原生js的掌握程度。实现了jQuery的部分功能。如选择元素、add、trigger、queue、dequeue、delay、animate、callback、deffer…等方法
Github地址:https://github.com/mytheart/my-projects/tree/master/projects/myjQuery
(function () {
function jQuery (selector) {
return new jQuery.prototype.init(selector);
}
jQuery.prototype.init = function (selector) {
// this = {};
// 选出 dom 并且包装成jQuery对象 返回
// id class
this.length = 0;
// null undefined dom
if (selector == null) {
return this;
}
if (typeof selector == 'string' && selector.indexOf('.') != -1) {
var dom = document.getElementsByClassName( selector.slice(1) );
}else if (typeof selector == 'string' && selector.indexOf('#') != -1) {
var dom = document.getElementById( selector.slice(1) );
}
if (selector instanceof Element || dom.length == undefined) {
this[0] = dom || selector;
this.length++;
}else {
// 基础铺垫
for (var i = 0; i < dom.length; i++) {
this[i] = dom[i];
this.length++
}
}
// return this;
}
jQuery.prototype.css = function (config) {
// 循环操作每一个dom
// 循环操作
for (var i = 0; i < this.length; i++) {
for (var attr in config) {
this[i].style[attr] = config[attr];
}
}
// 链式操作
return this;
}
jQuery.prototype.pushStack = function (dom) {
// dom newObj
if (dom.constructor != jQuery) {
dom = jQuery(dom);
}
dom.prevObject = this;
return dom;
}
jQuery.prototype.get = function (num) {
return num != null ? (num >= 0 ? this[num] : this[num + this.length]) : [].slice.call(this,