
上篇文章给大家介绍了jQuery的框架,有关jquery的基础知识可以参考下。
jQuery使用许久了,但是有一些API的实现实在想不通。下面将使用简化的代码来介绍,主要关注jQuery的实现思想。
相较于上一篇,代码更新了:21~78
(function(window, undefined){
function jQuery(sel){
return new jQuery.prototype.init(sel);
}
jQuery.prototype = {
constructor: jQuery,
init: function(sel){
if(typeof sel === string){
var that = this;
var nodeList = document.querySelectorAll(sel);
Array.prototype.forEach.call(nodeList, function(val, i){
that[i] = val;
})
this.selector = sel;
this.length = nodeList.length;
}
},
show: function(){
Array.prototype.forEach.call(this, function(node){
//if(node.style) continue; //textnode没有style
//删除style上的display:none
var display = node.style.display;
if(display === none){
//dispaly置为空后,css如果有display则css的生效
//否则默认的生效
node.style.display = ;
}
//元素display值为非默认值情况,需要还原为oldDisplay:div-