一 jquery是什么?
<1> jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team。
<2>jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是--WRITE LESS,DO MORE!
<3>它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器(IE 6.0+,FF 1.5+,Safari 2.0+,Opera 9.0+)。
<4>jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documents、events、实现动画效果,并且方便地为网站提供AJAX交互。
<5>jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。
二 什么是jQury对象?
jQuery 对象就是通过jQuery包装DOM对象后产生的对象。jQuery 对象是 jQuery 独有的. 如果一个对象是 jQuery 对象,那么它就可以使用 jQuery 里的方法: $(“#test”).html();
$("#test").html()
//意思是指:获取ID为test的元素内的HTML代码。其中html()是jQuery里的方法
// 这段代码等同于用DOM实现代码: document.getElementById(" test ").innerHTML;
//虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法.乱使用会报错
//约定:如果获取的是 jQuery 对象,那么要在变量前面加上$.
var $variable = jQuery 对象
var variable = DOM 对象
$variable[0]:jquery对象转为dom对象 $("#msg").html(); $("#msg")[0].innerHTML
jquery的基础语法:$(selector).action()
三 寻找元素(选择器和筛选器)
3.1 选择器
3.1.1 基本选择器
选择器 实例 选取 * $("*") 所有元素 #id $("#lastname") id="lastname" 的元素 .class $(".intro") 所有 class="intro" 的元素 element $("p") 所有 <p> 元素 .class.class $(".intro.demo") 所有 class="intro" 且 class="demo" 的元素
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="div">hello div</div> <a href="">click a</a><br> <a id="p1">pppp</a> <div class="outer"> outer <div class="inner"> inner <p>inner p</p> </div> </div> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $("*").css("font-size",'20px'); $("a").css("color","red"); $("#p1").css("color","yellow"); $(".outer").css("color","blue"); $(".inner .p").css("color","green") </script> </html>
3.1.2 层级选择器
$(".outer div") 向下所有div标签
$(".outer>div")
$(".outer+div") 下面
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <p>out p</p> <div class="outer">outer 0 div</div> <div class="outer">outer 1 div <div class="inner"> inner div <p>inner p</p> </div> <div class="inner2"> inner 2 div </div> <p>outer p</p> </div> <div class="outer2">outer2 div</div> <p>xiao lv</p> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $(".outer p").css("color","red"); $(".outer>div").css("color","yellow"); $(".outer+div").css("color","blue"); $(".outer~p").css("color","green"); </script> </html>
3.1.3 基本筛选器(少用)
$("li:first") 找到第一个li标签
$("li:last") 找到最后一个li标签
$("li:eq(2)") 找到第三个li标签
$("li:even") 所有偶数标签
$("li:odd") 所有基数标签
$("li:gt(1)") 从第二个li标签之后
$("li:lt(3)") 从第四个li标签之前
3.1.4 属性选择器
$("[id='div1']") 找到指定id标签
$("['lily'='nb'][id]") 找到所有指定标签,然后根据id筛选指定标签
$("[ssid ='"+sid+"']") 带变量属性筛选器,sid一个变量,ssid标签名
3.1.5 表单选择器
$("[type='text']")----->$(":text")
$("input:checked") 注意只适用于input标签
3.2 筛选器
3.2.1 过滤筛选器(推荐使用)
$("li").eq(2) 找到第三个li标签
$("li").first() 找到第一个li标签
$("li").last() 找到最后一个li标签
$("ul li").hasclass("test") 判断标签是否存在(结果是true or false)
.hasclass()示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="div1">hello div1</div> </body> <script src="jquery-3.1.1.js"></script> <script> document.write($("div").hasClass("div1")) </script> </html>
3.2.2 查找筛选器
$("div").children(".test") 查找div标签的儿子class=test的标签
$("div").find(".test") 查找div标签下属所有class=test的标签
$(".test").next() 查找class=test标签的下一个标签
$(".test").nextAll() 查找class=test标签的下面所有标签
$(".test").nextUntil(".end") 查找class=test标签下面所有标签直到找到class=end标签停止
$("div").prev() 查找class=test标签的上一个标签
$("div").prevAll() 查找class=test标签的上面所有标签
$("div").prevUntil() 和$(".test").nextUntil(".end") 相反
$(".test").parent() 查找class=test标签的父亲标签
$(".test").parents() 查找class=test标签的所有父亲标签
$(".test").parentUntil()
$("div").siblings() 查找div标签的所有兄弟标签
左侧菜单联动
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> <style> .outer{ height: 1000px; width: 100%; } .menu{ float: left; background-color: #8ca1c1; width: 30%; height: 100%; } .content{ float: right; background-color: #d47f39; width: 70%; height: 100%; } .hide{ display: none; } .title{ background-color: antiquewhite; line-height: 50px; color: #2459a2; } </style> </head> <body> <div class="outer"> <div class="menu"> <div class="item"> <div class="title" onclick="show(this);">菜单一</div> <div class="con"> <div>子菜单一</div> <div>子菜单一</div> <div>子菜单一</div> </div> </div> <div class="item"> <div class="title" onclick="show(this);">菜单二</div> <div class="con hide"> <div>子菜单二</div> <div>子菜单二</div> <div>子菜单二</div> </div> </div> <div class="item"> <div class="title" onclick="show(this);">菜单三</div> <div class="con hide"> <div>子菜单三</div> <div>子菜单三</div> <div>子菜单三</div> </div> </div> </div> <div class="content"></div> </div> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> function show(self){ $(self).next().removeClass('hide'); $(self).parent().siblings().children(".con").addClass("hide"); } </script> </html>
四 操作元素(属性,css,文档处理)
4.1 属性操作
--------------------------属性
$("").attr(); 增加/修改属性 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
$("").removeAttr();
$("").prop(); 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
$("").removeProp();
--------------------------CSS类
$("").addClass(class|fn) 增加class属性
$("").removeClass([class|fn]) 移除class
--------------------------HTML代码/文本/值
$("").html([val|fn]) 相当于js innerHTML
$("").text([val|fn]) 相当于js innerText
$("").val([val|fn|arr]) 相当于js value(只能取到标签的固有值value),主要用于input select option
---------------------------
$("").css("color","red") 修改标签的样式
attr() prop()区别
<input id="chk1" type="checkBox" />是否可见 <input id="chk2" type="checkBox" checked="checked" />是否可见 <script> //像checkBox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此 //需要使用prop方法去操作才能获得正确的结果。 // $("#chk1").attr("checked") // undefined // $("#chk1").prop("checked") // false // ---------手动选中的时候attr()获得到没有意义的undefined----------- // $("#chk1").attr("checked") // undefined // $("#chk1").prop("checked") // true console.log($("#chk1").prop("checked"));//false console.log($("#chk2").prop("checked"));//true console.log($("#chk1").attr("checked"));//undefined console.log($("#chk2").attr("checked"));//checked </script>
javsscript和jquery相同功能的方法的名字(左js,右jquery)
.innerHTML .html()
jquery循环遍历两种方式:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <p>11111</p> <p>11111</p> <p>11111</p> <p>11111</p> <div>22222</div> <div>22222</div> <div>22222</div> <div>22222</div> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> // js和jquery可以混用 arr = [11,22,33,44]; for (var i=0;i<arr.length;i++){ $('p').eq(i).html(arr[i]) } // 第一种循环遍历方式 $.each(arr,function(x,y){ document.write(x,' '); document.write(y,"<br>"); }); // 第二种循环遍历方式 $("div").each(function(){ document.write($(this),"<br>"); $(this).html('hello 第二种循环遍历方式') }) </script> </html>
jquery正反选示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <button onclick="selectall();">全选</button> <button onclick="cancel();">取消</button> <button onclick="reverse();">反选</button> <table border="1"> <tr> <td><input type="checkBox"></td> <td>111</td> </tr> <tr> <td><input type="checkBox"></td> <td>222</td> </tr> <tr> <td><input type="checkBox"></td> <td>333</td> </tr> <tr> <td><input type="checkBox"></td> <td>444</td> </tr> </table> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> function selectall(){ $(":checkBox").each(function () { $(this).prop("checked",true) }) } function cancel(){ $(":checkBox").each(function(){ $(this).prop("checked",false) }) } function reverse(){ $(":checkBox").each(function(){ $(this).prop("checked",!$(this).prop("checked")) }) } </script> </html>
实例之模态对话框
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>Title</title> <style> .back{ background-color: rebeccapurple; height: 2000px; } .shade{ position: fixed; top: 0; bottom: 0; left:0; right: 0; background-color: coral; opacity: 0.4; } .hide{ display: none; } .models{ position: fixed; top: 50%; left: 50%; margin-left: -100px; margin-top: -100px; height: 200px; width: 200px; background-color: gold; } </style> </head> <body> <div> <input id="ID1" type="button" value="click" onclick="action1(this)"> </div> <div class="shade hide"></div> <div class="models hide"> <input id="ID2" type="button" value="cancel" onclick="action2(this)"> </div> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> function action1(self){ $(self).parent().siblings().removeClass("hide"); } function action2(self){ $(self).parent().parent().children(".models,.shade").addClass("hide") } </script> </body> </html>
4.2 文档处理
内部插入(父亲插入标签到儿子)
$("").append(content|fn) ----->$("p").append("<b>Hello</b>");
$("").appendTo(content) ----->$("p").appendTo("div");
$("").prepend(content|fn) ----->$("p").prepend("<b>Hello</b>");
$("").prependTo(content) ----->$("p").prependTo("#foo");
外部插入(兄弟标签插入)
$("").after(content|fn) ----->$("p").after("<b>Hello</b>");
$("").before(content|fn) ----->$("p").before("<b>Hello</b>");
$("").insertAfter(content) ----->$("p").insertAfter("#foo");
$("").insertBefore(content) ----->$("p").insertBefore("#foo");
替换
$("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>");
复制
$("").clone([Even[,deepEven]])
内部插入代码示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="c1"> <p>PPP</p> </div> <button>add</button> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $("button").click(function(){ $('.c1').append("<h1>append hello world</h1>"); var $ele=$("<h1></h1>"); //创建标签 $ele.html("append Hello word 方法2"); $ele.css("color",'red'); $('.c1').append($ele); var $ele1=$("<h1></h1>"); $ele1.html("appendto Hello word 方法3"); $ele1.css("color",'red'); $ele1.appendTo('.c1'); var $ele2=$("<h1></h1>"); $ele2.html("prepend Hello word 方法4"); $ele2.css("color",'red'); $(".c1").prepend($ele2); var $ele3=$("<h1></h1>"); $ele3.html("prependto Hello word 方法5"); $ele3.css("color",'red'); $ele3.prependTo('.c1'); }) </script> </html>
外部插入代码示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="c1"> <p>PPP</p> </div> <button>add</button> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $("button").click(function(){ var $ele=$("<h1></h1>"); //创建标签 $ele.html("after Hello word"); $ele.css("color",'red'); $('.c1').after($ele); var $ele1=$("<h1></h1>"); $ele1.html("before Hello word"); $ele1.css("color",'red'); $('.c1').before($ele1); }); var $ele2=$("<h1></h1>"); $ele2.html("insertAfter Hello word"); $ele2.css("color",'red'); $ele2.insertAfter(".c1"); </script> </html>
替换代码示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="c1"> <p>PPP</p> </div> <div class="c2"> <p>PPP</p> </div> <button>add</button> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $("button").click(function(){ $('.c1').empty(); $(".c2").remove(); }) </script> </html>
复制(复制样式条)代码示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="outer"> <div class="item"> <button onclick="add(this)">+</button> <input type="text"> </div> </div> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> function add(self){ var $clone_obj=$(self).parent().clone(); // 把value值清空 $clone_obj.children(':text').prop("value",""); $clone_obj.children("button").html('-').attr("onclick","remove_obj(this)"); $(".outer").append($clone_obj); } function remove_obj(self){ $(self).parent().remove() } </script> </html>
4.3 css操作
CSS样式
$("").css(name|pro|[,val|fn]) 样式修改
位置方法
$("").offset([coordinates]) 获取对象 获取对象具体信息方法:.offset().top .offset().left
相对于视口的偏移量
$("").position() 相对于已定位的父标签的偏移量
$("").scrollTop([val]) 必须要有监听事件
$("").scrollLeft([val]) 必须要有监听事件
尺寸方法
$("").height([val|fn]) 标签高度
$("").width([val|fn]) 标签长度
$("").innerHeight() 标签内部高度(包括padding)
$("").innerWidth() 标签内部宽度
$("").outerHeight([soptions]) 标签外部高度(包括边框,margin)
$("").outerWidth([options]) 标签外部宽度
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; padding:0; } .div1,.div2{ width: auto; height: 800px; } .div1{ background-color: green; } .div2{ background-color: #e59373; } .returnTop{ position: fixed; right: 20px; bottom: 20px; width: 80px; height: 50px; background-color: #99aecb; line-height: 50px; font-size: 14px; text-align: center; } .hide{ display: none; } </style> </head> <body> <div class="div1"></div> <div class="div2"></div> <div class="returnTop hide" >返回顶部</div> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> window.onscroll=function(){ var current=$(window).scrollTop(); console.log(current); if(current>100){ $(".returnTop").removeClass("hide") } else { $(".returnTop").addClass("hide") } }; function returnTop(){ $(window).scrollTop(0); } </script> </html>
五 事件
5.1 页面载入
ready(fn) //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
$(document).ready(function(){}) -----简写------> $(function(){})
代码示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>1111</li> <li>2222</li> <li>3333</li> <li>4444</li> <li>5555</li> </ul> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> // $(document).ready(function(){ // $("ul li").html(5555); // }); // 简写 $(function(){ $("ul li").html(5555); }) </script> </html>
事件绑定代码示例
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>1111</li> <li>2222</li> <li>3333</li> <li>4444</li> <li>5555</li> </ul> <button>add</button> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> // 简写 // $("ul li").click(function(){ // alert('11111111111'); // }); // 绑定事件全写 $("ul li").bind("click", function () { alert('2222222222'); }); $("button").click(function () { var $ele = $('<li></li>'); var len = $("ul li").length; $ele.html((len + 1) * 1111); $('ul').append($ele) }); // 解除绑定 // $("ul li").unbind("click") </script> </html>
事件代码坑注意事项:
1、绑定时间不能使用索引取值,只能使用seq如下面写法是错误:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>1111</li> <li>2222</li> <li>3333</li> <li>4444</li> <li>5555</li> </ul> <button>add</button> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> btns =$('.li') console.log(btns) for (i=0;i<btns.length;i++){ console.log(btns[i]) console.log('使用索引绑定时间') btns[i].click(function (){ alert('11111111') }) console.log('事件结束') } </script>
5.2 事件委托
$("").on(eve,[selector],[data],fn) 选择元素上绑定一个或多个事件的事件处理函数
.on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如:
$('ul').on('click','li',function(){console.log('click');})就是筛选出ul下的li给其绑定 click事件
[selector]参数的好处:
$('ul li').on('click',function(){console.log('click');})的绑定方式和
$('ul li').bind('click',function(){console.log('click');})一样;我通过js给ul添加了一个
li:$('ul').append('<li>js new li<li>');这个新加的li是不会被绑上click事件的
但是用$('ul').on('click',function(){console.log('click');}方式绑定,然后动态添加
li:$('ul').append('<li>js new li<li>');这个新生成的li被绑上了click事件
[data]参数的调用:
function myHandler(event) {
alert(event.data.foo);
}
$("li").on("click",{foo: "bar"},myHandler)
事件委托代码示例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>1111</li> <li>2222</li> <li>3333</li> <li>4444</li> <li>5555</li> </ul> <button>add</button> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> // 事件委托简写 // $("ul").on("click","li", function(){ // alert('11111111111'); // }); // 事件委托全写 $("ul").on("li").bind("click",function(){ alert('2222222222'); }); $("button").click(function(){ var $ele=$('<li></li>'); var len=$("ul li").length; $ele.html((len+1)*1111); $('ul').append($ele) }); // 解除绑定 // $("ul li").unbind("click") </script> </html>
面板拖动代码示例
<!DOCTYPE html> <html> <head lang="en"> <Meta charset="UTF-8"> <title></title> </head> <body> <div style="border: 1px solid #ddd;width: 600px;position: absolute;"> <div id="title" style="background-color: black;height: 40px;color: white;"> 标题 </div> <div style="height: 300px;"> 内容 </div> </div> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $(function () { // 页面加载完成之后自动执行 $('#title').mouSEOver(function () { $(this).css('cursor', 'move'); }).mousedown(function (e) { //console.log($(this).offset()); var _event = e || window.event; // 原始鼠标横纵坐标位置 var ord_x = _event.clientX; var ord_y = _event.clientY; var parent_left = $(this).parent().offset().left; var parent_top = $(this).parent().offset().top; $(this).bind('mousemove', function (e) { var _new_event = e || window.event; var new_x = _new_event.clientX; var new_y = _new_event.clientY; var x = parent_left + (new_x - ord_x); var y = parent_top + (new_y - ord_y); $(this).parent().css('left', x + 'px'); $(this).parent().css('top', y + 'px'); }) }).mouseup(function () { $(this).unbind('mousemove'); }); }) </script> </body> </html>
六 动画效果
.show() 显示 .show(1000) 表示花费1秒钟时间完全显示
.hide() 隐藏
.toggle() 切换(显示和隐藏相互切换)
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div>hello</div> <button onclick="f1()">显示</button> <button onclick="f2()">隐藏</button> <button onclick="f3()">切换</button> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> function f1(){ $('div').show(1000) } function f2(){ $("div").hide(1000) } function f3(){ $("div").toggle(1000) } </script> </html>
slideDown() 向下显示
slideUp() 向上隐藏
slideToggle() 显示/隐藏切换
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <style> #content{ text-align: center; background-color: lightblue; border:solid 1px red; display: none; padding: 50px; } </style> <body> <div id="slideDown">出现</div> <div id="slideUp">隐藏</div> <div id="slideToggle">toggle</div> <div id="content">hello world</div> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function(){ $("#slideDown").click(function(){ $("#content").slideDown(1000); }); $("#slideUp").click(function(){ $("#content").slideUp(1000); }); $("#slideToggle").click(function(){ $("#content").slideToggle(1000); }) }); </script> </html>
6.3 淡入淡出
fadeIn() 淡入已隐藏的元素
fadeOut() 淡出可见元素
fadeToggle() 在 fadeIn() 与 fadeOut() 方法之间进行切换
fadeTo() 允许渐变为给定的不透明度(值介于 0 与 1 之间)
代码示例
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <style> #content{ text-align: center; background-color: lightblue; border:solid 1px red; display: none; padding: 50px; } </style> <body> <button id="in">淡入</button> <button id="out">淡出</button> <button id="toggle">fadetoggle</button> <button id="fadeto">fadeto</button> <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div> </body> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function(){ $("#in").click(function(){ $("#id1").fadeIn(1000); }); $("#out").click(function(){ $("#id1").fadeOut(1000); }); $("#toggle").click(function(){ $("#id1").fadeToggle(1000); }); $("#fadeto").click(function(){ $("#id1").fadeTo(1000,0.4); }); }); </script> </html>
6.4 回调函数
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>Title</title> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <button>hide</button> <p>helloworld helloworld helloworld</p> <script> $("button").click(function(){ $("p").hide(1000,function(){ alert($(this).html()) }) }) </script> </body> </html>
<script> $.extend(object) //为JQuery 添加一个静态方法。 $.fn.extend(object) //为JQuery实例添加一个方法。 jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }); console.log($.min(3,4)); //----------------------------------------------------------------------- $.fn.extend({ "print":function(){ console.log($(this).html()) } }); $("p").print(); </script>
7.2 定义作用域
定义一个JQuery插件,首先要把这个插件的代码放在一个不受外界干扰的地方。如果用专业些的话来说就是要为这个插件定义私有作用域。外部的代码不能直接访问插件内部的代码。插件内部的代码不污染全局变量。在一定的作用上解耦了插件与运行环境的依赖。
(function(a,b){return a+b})(3,5) (function ($) { })(jQuery); //相当于 var fn = function ($) { }; fn(jQuery);
7.3 默认参数
定义了jQuery插件之后,如果希望某些参数具有默认值,那么可以以这种方式来指定。
/step01 定义JQuery的作用域 (function ($) { //step03-a 插件的默认值属性 var defaults = { prevId: 'prevBtn', prevText: 'PrevIoUs', nextId: 'nextBtn', nextText: 'Next' //…… }; //step06-a 在插件里定义方法 var showLink = function (obj) { $(obj).append(function () { return "(" + $(obj).attr("href") + ")" }); } //step02 插件的扩展方法名称 $.fn.easySlider = function (options) { //step03-b 合并用户自定义属性,默认属性 var options = $.extend(defaults, options); //step4 支持JQuery选择器 //step5 支持链式调用 return this.each(function () { //step06-b 在插件里定义方法 showLink(this); }); } })(jQuery);
8.新建标签
<script> var link = $("<a/>") </script>