jQuery简介
版本: 1.x:兼容ie678,使用最为广泛的,官方只做BUG维护,功能不再新增。因此一般项目来说,使用1.x版本就可以了,最终版本:1.12.4 (2016年5月20日) 2.x:不兼容ie678,很少有人使用,官方只做BUG维护,功能不再新增。如果不考虑兼容低版本的浏览器可以使用2.x,最终版本:2.2.4 (2016年5月20日) 3.x:不兼容ie678,只支持最新的浏览器。除非特殊要求,一般不会使用3.x版本的,很多老的jQuery插件不支持这个版本。目前该版本是官方主要更新维护的版本。本地下载:https://www.jb51.net/zt/jquerydown.htm
在线引入:http://www.bootcdn.cn/jquery/
支持所有css2选择器 大部分css3选择
不能引号引起来的:this document window
所有的点击事件都在原生js上面去掉on
$是Jquery对外开放的唯一接口
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>//在线引入 <script> var aP = $(".dv1 p"); console.log(aP); console.log($); /* 遍历的方法 each index 索引 obj 遍历的对象 */ aP.each(function(index,obj){ consoloe.log(index+'---'+obj); }); /* 设置css样式 要传json格式*/ aP.css({ "background":"deeppink" "color":"#ccc" }); /* html() 代替了原生innerHTML */ aP.html("还是奇迹"); /* 链式调用 */ $(".box p").css({"background":"deeppink","color":"#fff"}).html("我爱你就是快乐!") </script>
注意:事项
/* 为了不污染全局的变量,所有一般封装的函数都会放在函数表达式自执行里面 */ (function(){ window.a = 10;//把a变成全局变量 })();简单封装三个方法:
封装(1)each、css、html
/* 用函数表达式来封装 */ (function () { /******************************/ /*************接口*************/ /******************************/ function $(select) { return new Fn(select); } /******************************/ /**********构造函数************/ /******************************/ function Fn(elements) { this.eale = document.querySelectorAll(elements); } /* each方法 */ Fn.prototype.each = function(callBack){ for( var i=0; i<this.eale.length; i++ ){ callBack && callBack.call(this.eale[i],i,this.eale[i]);//第一个this是call回调函数指向,第二个参数是对象下标,第三个参数是被遍历对象 } } /* css方法 */ Fn.prototype.css = function(Json){ this.each(function () { for (var k in Json) { this.style[k] = Json[k]; } }); } /* html方法 */ Fn.prototype.html = function(str){ this.each(function () { this.innerHTML = str; }); } /* 向外暴露的唯一函数 */ window.$ = $; })();封装(2)升级版 --- each、css、html
/* 用函数表达式来封装 */ (function () { /******************************/ /*************接口*************/ /******************************/ function $(select) { return new Fn(select); } /******************************/ /**********构造函数************/ /******************************/ function Fn(elements) { this.eale = document.querySelectorAll(elements); } /* 添加原型的方法 */ function add(Json){ for (var k in Json) { Fn.prototype[k] = Json[k]; } } /* 添加原型 */ add({ /* 添加each方法 */ each:function(callBack){ for( var i=0; i<this.eale.length; i++ ){ callBack && callBack.call(this.eale[i],i,this.eale[i]); } }, /* 添加css方法 */ css:function(Json){ this.each(function () { for (var k in Json) { this.style[k] = Json[k]; } }); }, /* 添加html方法 */ html:function(str){ this.each(function () { this.innerHTML = str; }); } }); /* 向外暴露的唯一函数 */ window.$ = $; })();