<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>1</div>
<div>2</div>
<p>3</p>
<span id="spa">4</span>
</body>
<script type="text/javascript">
(function(global){
function jquery(selectors){
return new jquery.fn.init(selectors);
}
//简化优化:给jquery添加一个属性fn
jquery.fn=jquery.prototype={
constructor:jquery,
init:function(selectors){
var elements=document.querySelectorAll(selectors);
for(var i=0;i<elements.length;i++){
this[i]=elements[i];//给this创建属性从0开始的i
}
this.length=elements.length;
},
css:function(name,value){
for(var i=0;i<this.length;i++){
this[i].style[name]=value;
}
}
}
//重点:为了让init实例对象访问到css方法
jquery.fn.init.prototype=jquery.fn;
//给window对象添加属性$和jquery,并设置值为jquery
window.$=window.jquery=jquery;
})(window)
$('div').css('color','red');
$('#spa').css('color','yellow')
</script>
</html>
JS库封装改进的简化
最新推荐文章于 2023-03-18 16:59:11 发布