用最简单的代码还原jQuery最核心的思路
html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div>abc ...</div>
<p>jjjjj</p>
</body>
<script type="text/javascript">
console.log('ppp',$('p'));
$("p").css("background-color", "red");
// $("p").html('这是通过 jquery 来改变值的');
</script>
</html>
js
var $ = function(selector){
return zepto.init(selector);
}
var zepto = {};
zepto.init = function(selector){
var slice = Array.prototype.slice;
var dom = slice.call(document.querySelectorAll(selector));
return zepto.Z(dom,selector);
}
zepto.Z = function(dom,selector){
return new Z(dom,selector);
}
function Z(dom,selector){
var i,len = dom?dom.length:0;
for(i=0;i<len;i++) this[i] = dom[i];
this.length = len;
this.selector = selector || '';
}
$.fn={
constructor:zepto.Z,
css:function(key,val){
console.log('css ....',this);
this[0].style['background-color'] = 'yellow';
},
html:function(val){
console.log('html ....');
this[0].innerHTML = val;
}
}
zepto.Z.prototype = Z.prototype = $.fn;
js 再简洁点
// 简化版,但是此处 没有支持扩展,主要是 $.fn 里面加 contructor:zepo.Z
$ = function(selector){
return zepo.Init(selector);
}
var zepo = {
Init:function(selector){
return new Z(selector)
}
}
function Z(selector){
var list = document.querySelectorAll(selector);
var i,len= list.length>0 ? list.length : 0;
for(i=0;i<len;i++) this[i] = list[i];
if(selector) this.selector = selector;
}
$.fn={
css:function(key,val){
console.log('css ....',this);
// this[0].style['background-color'] = 'red';
//
this[0].style[key] = val;
},
html:function(val){
console.log('html ....');
this[0].innerHTML = val;
}
}
Z.prototype = $.fn;
网友评论