jQuery总结

JQuery-----总结

 

一、jQuery是什么?                                                                               

<1> jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team。

<2>jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!

<3>它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器

<4>jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。

<5>jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。

二、什么是jQuery对象?                                                                         

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")   $(".class")  $("element")  $(".class,p,div")

3.1.2 层级选择器    

$(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")

3.1.3 基本筛选器      

$("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")

3.1.4 属性选择器    

$('[id="div1"]')   $('["alex="sb"][id]')

3.1.5 表单选择器     

$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")

实例之左侧菜单

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>left_menu</title>
 6     <script>
 7           function show(self){
 8               $(self).next().removeClass("hide");
 9               $(self).parent().siblings().children(".con").addClass("hide");
10 
11           }
12     </script>
13     <style>
14           .menu{
15               height: 500px;
16               width: 30%;
17               background-color: gainsboro;
18               float: left;
19           }
20           .content{
21               height: 500px;
22               width: 70%;
23               background-color: rebeccapurple;
24               float: left;
25           }
26          .title{
27              line-height: 50px;
28              background-color: #425a66;
29              color: forestgreen;}
30 
31 
32          .hide{
33              display: none;
34          }
35 
36 
37     </style>
38 </head>
39 <body>
40 
41 <div class="outer">
42     <div class="menu">
43         <div class="item">
44             <div class="title" onclick="show(this);">菜单一</div>
45             <div class="con">
46                 <div>111</div>
47                 <div>111</div>
48                 <div>111</div>
49             </div>
50         </div>
51         <div class="item">
52             <div class="title" onclick="show(this);">菜单二</div>
53             <div class="con hide">
54                 <div>111</div>
55                 <div>111</div>
56                 <div>111</div>
57             </div>
58         </div>
59         <div class="item">
60             <div class="title" onclick="show(this);">菜单三</div>
61             <div class="con hide">
62                 <div>111</div>
63                 <div>111</div>
64                 <div>111</div>
65             </div>
66         </div>
67 
68     </div>
69     <div class="content"></div>
70 
71 </div>
72 
73 </body>
74 </html>
View Code

实例之tab切换

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>tab</title>
 6     <script>
 7            function tab(self){
 8                var index=$(self).attr("xxx");
 9                $("#"+index).removeClass("hide").siblings().addClass("hide");
10                $(self).addClass("current").siblings().removeClass("current");
11 
12            }
13     </script>
14     <style>
15         *{
16             margin: 0px;
17             padding: 0px;
18         }
19         .tab_outer{
20             margin: 0px auto;
21             width: 60%;
22         }
23         .menu{
24             background-color: #cccccc;
25             /*border: 1px solid red;*/
26             line-height: 40px;
27         }
28         .menu li{
29             display: inline-block;
30         }
31         .menu a{
32             border-right: 1px solid red;
33             padding: 11px;
34         }
35         .content{
36             background-color: tan;
37             border: 1px solid green;
38             height: 300px;
39         }
40         .hide{
41             display: none;
42         }
43 
44         .current{
45             background-color: darkgray;
46             color: yellow;
47             border-top: solid 2px rebeccapurple;
48         }
49     </style>
50 </head>
51 <body>
52       <div class="tab_outer">
53           <ul class="menu">
54               <li xxx="c1" class="current" onclick="tab(this);">菜单一</li>
55               <li xxx="c2" onclick="tab(this);">菜单二</li>
56               <li xxx="c3" onclick="tab(this);">菜单三</li>
57           </ul>
58           <div class="content">
59               <div id="c1">内容一</div>
60               <div id="c2" class="hide">内容二</div>
61               <div id="c3" class="hide">内容三</div>
62           </div>
63 
64       </div>
65 </body>
66 </html>
View Code

3.2 筛选器

3.2.1  过滤筛选器     

$("li").eq(2)  $("li").first()  $("ul li").hasclass("test")

 3.2.2  查找筛选器

 $("div").children(".test")     $("div").find(".test")  
                               
 $(".test").next()    $(".test").nextAll()    $(".test").nextUntil() 
                           
 $("div").prev()  $("div").prevAll()  $("div").prevUntil()   
                        
 $(".test").parent()  $(".test").parents()  $(".test").parentUntil() 

 $("div").siblings()

四、操作元素(属性,css,文档处理)                                                          

4.1 属性操作

--------------------------属性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
--------------------------CSS类
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------HTML代码/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])
---------------------------
$("").css("color","red")

注意:

 1 <input id="chk1" type="checkbox" />是否可见
 2 <input id="chk2" type="checkbox" checked="checked" />是否可见
 3 
 4 
 5 
 6 <script>
 7 
 8 //对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
 9 //对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
10 //像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此
11 //需要使用prop方法去操作才能获得正确的结果。
12 
13 
14 //    $("#chk1").attr("checked")
15 //    undefined
16 //    $("#chk1").prop("checked")
17 //    false
18 
19 //  ---------手动选中的时候attr()获得到没有意义的undefined-----------
20 //    $("#chk1").attr("checked")
21 //    undefined
22 //    $("#chk1").prop("checked")
23 //    true
24 
25     console.log($("#chk1").prop("checked"));//false
26     console.log($("#chk2").prop("checked"));//true
27     console.log($("#chk1").attr("checked"));//undefined
28     console.log($("#chk2").attr("checked"));//checked
29 </script>
30 
31 attr和prop
attr和prop

实例之全反选

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="jquery-1.11.3.min.js"></script>
 7     <script>
 8 
 9              function selectall(){
10 
11                  $("table :checkbox").prop("checked",true)
12              }
13              function cancel(){
14 
15                  $("table :checkbox").prop("checked",false)
16              }
17 
18              function reverse(){
19 
20 
21                  //                 var idlist=$("table :checkbox")
22 //                 for(var i=0;i<idlist.length;i++){
23 //                     var element=idlist[i];
24 //
25 //                     var ischecked=$(element).prop("checked")
26 //                     if (ischecked){
27 //                         $(element).prop("checked",false)
28 //                     }
29 //                     else {
30 //                         $(element).prop("checked",true)
31 //                     }
32 //
33 //                 }
34 //    jquery循环的两种方式
35                  //方式一
36 //                 li=[10,20,30,40]
37 //                 dic={name:"yuan",sex:"male"}
38 //                 $.each(li,function(i,x){
39 //                     console.log(i,x)
40 //                 })
41 
42                  //方式二
43 //                    $("tr").each(function(){
44 //                        console.log($(this).html())
45 //                    })
46 
47 
48 
49                  $("table :checkbox").each(function(){
50 
51                      $(this).prop("checked",!$(this).prop("checked"));
52 
53 //                     if ($(this).prop("checked")){
54 //                         $(this).prop("checked",false)
55 //                     }
56 //                     else {
57 //                         $(this).prop("checked",true)
58 //                     }
59 
60                      // 思考:如果用attr方法可以实现吗?
61 
62 
63                  });
64              }
65 
66     </script>
67 </head>
68 <body>
69 
70      <button onclick="selectall();">全选</button>
71      <button onclick="cancel();">取消</button>
72      <button onclick="reverse();">反选</button>
73 
74      <table border="1">
75          <tr>
76              <td><input type="checkbox"></td>
77              <td>111</td>
78          </tr>
79          <tr>
80              <td><input type="checkbox"></td>
81              <td>222</td>
82          </tr>
83          <tr>
84              <td><input type="checkbox"></td>
85              <td>333</td>
86          </tr>
87          <tr>
88              <td><input type="checkbox"></td>
89              <td>444</td>
90          </tr>
91      </table>
92 
93 
94 
95 </body>
96 </html>
View Code

实例之模态对话框

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         .back{
 8             background-color: rebeccapurple;
 9             height: 2000px;
10         }
11 
12         .shade{
13             position: fixed;
14             top: 0;
15             bottom: 0;
16             left:0;
17             right: 0;
18             background-color: coral;
19             opacity: 0.4;
20         }
21 
22         .hide{
23             display: none;
24         }
25 
26         .models{
27             position: fixed;
28             top: 50%;
29             left: 50%;
30             margin-left: -100px;
31             margin-top: -100px;
32             height: 200px;
33             width: 200px;
34             background-color: gold;
35 
36         }
37     </style>
38 </head>
39 <body>
40 <div class="back">
41     <input id="ID1" type="button" value="click" onclick="action1(this)">
42 </div>
43 
44 <div class="shade hide"></div>
45 <div class="models hide">
46     <input id="ID2" type="button" value="cancel" onclick="action2(this)">
47 </div>
48 
49 
50 <script src="jquery-1.11.3.min.js"></script>
51 <script>
52 
53     function action1(self){
54         $(self).parent().siblings().removeClass("hide");
55 
56     }
57     function action2(self){
58         //$(self).parent().parent().children(".models,.shade").addClass("hide")
59 
60         $(self).parent().addClass("hide").prev().addClass("hide")
61 
62     }
63 </script>
64 </body>
65 </html>
View Code

4.2 文档处理

//创建一个标签对象
    $("<p>")


//内部插入

    $("").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>");

//删除

    $("").empty()
    $("").remove([expr])

//复制

    $("").clone([Even[,deepEven]])

实例之复制样式条

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 
 7 </head>
 8 <body>
 9             <div class="outer">
10                 <div class="item">
11                         <input type="button" value="+" onclick="add(this);">
12                         <input type="text">
13                 </div>
14             </div>
15 
16 <script src="jquery-1.11.3.min.js"></script>
17     <script>
18             //var $clone_obj=$(self).parent().clone();  // $clone_obj放在这个位置可以吗?
19             function add(self){
20                 // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
21                  var $clone_obj=$(self).parent().clone();
22                  $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
23                  $(self).parent().parent().append($clone_obj);
24             }
25            function removed(self){
26 
27                $(self).parent().remove()
28 
29            }
30 
31     </script>
32 </body>
33 </html>
View Code

4.3 css操作

CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])
        $("").position()
        $("").scrollTop([val])
        $("").scrollLeft([val])
    尺寸
        $("").height([val|fn])
        $("").width([val|fn])
        $("").innerHeight()
        $("").innerWidth()
        $("").outerHeight([soptions])
        $("").outerWidth([options])

实例返回顶部

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="js/jquery-2.2.3.js"></script>
 7     <script>
 8 
 9 
10           window.onscroll=function(){
11 
12               var current=$(window).scrollTop();
13               console.log(current)
14               if (current>100){
15 
16                   $(".returnTop").removeClass("hide")
17               }
18               else {
19               $(".returnTop").addClass("hide")
20           }
21           }
22 
23 
24            function returnTop(){
25 //               $(".div1").scrollTop(0);
26 
27                $(window).scrollTop(0)
28            }
29 
30 
31 
32 
33     </script>
34     <style>
35         body{
36             margin: 0px;
37         }
38         .returnTop{
39             height: 60px;
40             width: 100px;
41             background-color: darkgray;
42             position: fixed;
43             right: 0;
44             bottom: 0;
45             color: greenyellow;
46             line-height: 60px;
47             text-align: center;
48         }
49         .div1{
50             background-color: orchid;
51             font-size: 5px;
52             overflow: auto;
53             width: 500px;
54         }
55         .div2{
56             background-color: darkcyan;
57         }
58         .div3{
59             background-color: aqua;
60         }
61         .div{
62             height: 300px;
63         }
64         .hide{
65             display: none;
66         }
67     </style>
68 </head>
69 <body>
70      <div class="div1 div">
71          <p>hello</p>
72          <p>hello</p>
73          <p>hello</p>
74          <p>hello</p>
75          <p>hello</p>
76          <p>hello</p>
77          <p>hello</p>
78          <p>hello</p>
79          <p>hello</p>
80          <p>hello</p>
81          <p>hello</p>
82          <p>hello</p>
83          <p>hello</p>
84          <p>hello</p>
85          <p>hello</p>
86          <p>hello</p>
87          <p>hello</p>
88          <p>hello</p>
89 
90      </div>
91      <div class="div2 div"></div>
92      <div class="div3 div"></div>
93      <div class="returnTop hide" onclick="returnTop();">返回顶部</div>
94 </body>
95 </html>
View Code

五、事件                                                                                               

页面载入
    ready(fn)  //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
    $(document).ready(function(){}) -----------> $(function(){})

事件处理
    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。

    //  .on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如:
    //  $('ul').on('click', 'li', function(){console.log('click');})就是筛选出ul下的li给其绑定
    //  click事件;

    [selector]参数的好处:
        好处在于.on方法为动态添加的元素也能绑上指定事件;如:

        //$('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', 'li', 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)

实例之面板拖动

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <div style="border: 1px solid #ddd; 600px;position: absolute;">
 9         <div id="title" style="background-color: black;height: 40px;color: white;">
10             标题
11         </div>
12         <div style="height: 300px;">
13             内容
14         </div>
15     </div>
16 <script type="text/javascript" src="jquery-2.2.3.js"></script>
17 <script>
18     $(function(){
19         // 页面加载完成之后自动执行
20         $('#title').mouseover(function(){
21             $(this).css('cursor','move');
22         }).mousedown(function(e){
23             //console.log($(this).offset());
24             var _event = e || window.event;
25             // 原始鼠标横纵坐标位置
26             var ord_x = _event.clientX;
27             var ord_y = _event.clientY;
28 
29             var parent_left = $(this).parent().offset().left;
30             var parent_top = $(this).parent().offset().top;
31 
32             $(this).bind('mousemove', function(e){
33                 var _new_event = e || window.event;
34                 var new_x = _new_event.clientX;
35                 var new_y = _new_event.clientY;
36 
37                 var x = parent_left + (new_x - ord_x);
38                 var y = parent_top + (new_y - ord_y);
39 
40                 $(this).parent().css('left',x+'px');
41                 $(this).parent().css('top',y+'px');
42 
43             })
44         }).mouseup(function(){
45             $(this).unbind('mousemove');
46         });
47     })
48 </script>
49 </body>
50 </html>
View Code

实例之放大镜

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>bigger</title>
  6     <style>
  7         *{
  8             margin: 0;
  9             padding:0;
 10         }
 11         .outer{
 12             height: 350px;
 13             width: 350px;
 14             border: dashed 5px cornflowerblue;
 15         }
 16         .outer .small_box{
 17             position: relative;
 18         }
 19         .outer .small_box .float{
 20             height: 175px;
 21             width: 175px;
 22             background-color: darkgray;
 23             opacity: 0.4;
 24             fill-opacity: 0.4;
 25             position: absolute;
 26             display: none;
 27 
 28         }
 29 
 30         .outer .big_box{
 31             height: 400px;
 32             width: 400px;
 33             overflow: hidden;
 34             position:absolute;
 35             left: 360px;
 36             top: 0px;
 37             z-index: 1;
 38             border: 5px solid rebeccapurple;
 39             display: none;
 40 
 41 
 42         }
 43         .outer .big_box img{
 44             position: absolute;
 45             z-index: 5;
 46         }
 47 
 48 
 49     </style>
 50 </head>
 51 <body>
 52 
 53         <div class="outer">
 54             <div class="small_box">
 55                 <div class="float"></div>
 56                 <img src="small.jpg">
 57 
 58             </div>
 59             <div class="big_box">
 60                 <img src="big.jpg">
 61             </div>
 62 
 63         </div>
 64 
 65 
 66 <script src="jquery-2.1.4.min.js"></script>
 67 <script>
 68 
 69     $(function(){
 70 
 71           $(".small_box").mouseover(function(){
 72 
 73               $(".float").css("display","block");
 74               $(".big_box").css("display","block")
 75 
 76           });
 77           $(".small_box").mouseout(function(){
 78 
 79               $(".float").css("display","none");
 80               $(".big_box").css("display","none")
 81 
 82           });
 83 
 84           $(".small_box").mousemove(function(e){
 85 
 86               var _event=e || window.event;
 87 
 88               var float_width=$(".float").width();
 89               var float_height=$(".float").height();
 90 
 91               console.log(float_height,float_width);
 92 
 93               var float_height_half=float_height/2;
 94               var float_width_half=float_width/2;
 95               console.log(float_height_half,float_width_half);
 96 
 97 
 98                var small_box_width=$(".small_box").height();
 99                var small_box_height=$(".small_box").width();
100 
101 
102 
103 //  鼠标点距离左边界的长度与float应该与左边界的距离差半个float的width,height同理
104               var mouse_left=_event.clientX-float_width_half;
105               var mouse_top=_event.clientY-float_height_half;
106 
107               if(mouse_left<0){
108                   mouse_left=0
109               }else if (mouse_left>small_box_width-float_width){
110                   mouse_left=small_box_width-float_width
111               }
112 
113 
114               if(mouse_top<0){
115                   mouse_top=0
116               }else if (mouse_top>small_box_height-float_height){
117                   mouse_top=small_box_height-float_height
118               }
119 
120                $(".float").css("left",mouse_left+"px");
121                $(".float").css("top",mouse_top+"px")
122 
123                var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
124                var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);
125 
126               console.log(percentX,percentY)
127 
128                $(".big_box img").css("left", -percentX*mouse_left+"px")
129                $(".big_box img").css("top", -percentY*mouse_top+"px")
130           })
131     })
132 
133 
134 </script>
135 </body>
136 </html>
View Code

六、动画效果                                                                                         

显示隐藏

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="jquery-2.1.4.min.js"></script>
 7     <script>
 8 
 9 $(document).ready(function() {
10     $("#hide").click(function () {
11         $("p").hide(1000);
12     });
13     $("#show").click(function () {
14         $("p").show(1000);
15     });
16 
17 //用于切换被选元素的 hide() 与 show() 方法。
18     $("#toggle").click(function () {
19         $("p").toggle();
20     });
21 })
22 
23     </script>
24     <link type="text/css" rel="stylesheet" href="style.css">
25 </head>
26 <body>
27 
28 
29     <p>hello</p>
30     <button id="hide">隐藏</button>
31     <button id="show">显示</button>
32     <button id="toggle">切换</button>
33 
34 </body>
35 </html>
View Code

滑动

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="jquery-2.1.4.min.js"></script>
 7     <script>
 8     $(document).ready(function(){
 9      $("#slideDown").click(function(){
10          $("#content").slideDown(1000);
11      });
12       $("#slideUp").click(function(){
13          $("#content").slideUp(1000);
14      });
15       $("#slideToggle").click(function(){
16          $("#content").slideToggle(1000);
17      })
18   });
19     </script>
20     <style>
21 
22         #content{
23             text-align: center;
24             background-color: lightblue;
25             border:solid 1px red;
26             display: none;
27             padding: 50px;
28         }
29     </style>
30 </head>
31 <body>
32 
33     <div id="slideDown">出现</div>
34     <div id="slideUp">隐藏</div>
35     <div id="slideToggle">toggle</div>
36 
37     <div id="content">helloworld</div>
38 
39 </body>
40 </html>
View Code

淡入淡出

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="jquery-2.1.4.min.js"></script>
 7     <script>
 8     $(document).ready(function(){
 9    $("#in").click(function(){
10        $("#id1").fadeIn(1000);
11 
12 
13    });
14     $("#out").click(function(){
15        $("#id1").fadeOut(1000);
16 
17    });
18     $("#toggle").click(function(){
19        $("#id1").fadeToggle(1000);
20 
21 
22    });
23     $("#fadeto").click(function(){
24        $("#id1").fadeTo(1000,0.4);
25 
26    });
27 });
28 
29 
30 
31     </script>
32 
33 </head>
34 <body>
35       <button id="in">fadein</button>
36       <button id="out">fadeout</button>
37       <button id="toggle">fadetoggle</button>
38       <button id="fadeto">fadeto</button>
39 
40       <div id="id1" style="display:none;  80px;height: 80px;background-color: blueviolet"></div>
41 
42 </body>
43 </html>
View Code

回调函数

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="jquery-2.1.4.min.js"></script>
 7 
 8 </head>
 9 <body>
10   <button>hide</button>
11   <p>helloworld helloworld helloworld</p>
12 
13 
14 
15  <script>
16    $("button").click(function(){
17        $("p").hide(1000,function(){
18            alert($(this).html())
19        })
20 
21    })
22     </script>
23 </body>
24 </html>
View Code

七、扩展方法 (插件机制)                                                                         

一 用JQuery写插件时,最核心的方两个方法

<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(){
        for (var i=0;i<this.length;i++){
            console.log($(this)[i].innerHTML)
        }

    }
});

$("p").print();
</script>

二 定义作用域

      定义一个JQuery插件,首先要把这个插件的代码放在一个不受外界干扰的地方。如果用专业些的话来说就是要为这个插件定义私有作用域。外部的代码不能直接访问插件内部的代码。插件内部的代码不污染全局变量。在一定的作用上解耦了插件与运行环境的依赖。

(function(a,b){return a+b})(3,5)

       (function ($) { })(jQuery);
//相当于
        var fn = function ($) { };
        fn(jQuery);

 三 默认参数

定义了jQuery插件之后,如果希望某些参数具有默认值,那么可以以这种方式来指定。

 1 /step01 定义JQuery的作用域
 2 (function ($) {
 3     //step03-a 插件的默认值属性
 4     var defaults = {
 5         prevId: 'prevBtn',
 6         prevText: 'Previous',
 7         nextId: 'nextBtn',
 8         nextText: 'Next'
 9         //……
10     };
11     //step06-a 在插件里定义方法
12     var showLink = function (obj) {
13         $(obj).append(function () { return "(" + $(obj).attr("href") + ")" });
14     }
15 
16     //step02 插件的扩展方法名称
17     $.fn.easySlider = function (options) {
18         //step03-b 合并用户自定义属性,默认属性
19         var options = $.extend(defaults, options);
20         //step4 支持JQuery选择器
21         //step5 支持链式调用
22         return this.each(function () {
23             //step06-b 在插件里定义方法
24             showLink(this);
25         });
26     }
27 })(jQuery);
View Code

八、经典实例练习                                                                                   

实例之注册验证

  1 <form class="Form">
  2 
  3     <p><input class="v1" type="text" name="username" mark="用户名"></p>
  4     <p><input class="v1" type="text" name="email" mark="邮箱"></p>
  5     <p><input class="v1" type="submit" value="submit"  onclick="return validate()"></p>
  6 
  7 </form>
  8 
  9 <script src="jquery-3.1.1.js"></script>
 10 <script>
 11     // 注意:
 12     // DOM对象--->jquery对象    $(DOM)
 13     // jquery对象--->DOM对象    $("")[0]
 14 
 15     //---------------------------------------------------------
 16 
 17 
 18     // DOM绑定版本
 19     function validate(){
 20 
 21         flag=true;
 22 
 23         $("Form .v1").each(function(){
 24             $(this).next("span").remove();// 防止对此点击按钮产生多个span标签
 25               var value=$(this).val();
 26             if (value.trim().length==0){
 27                  var mark=$(this).attr("mark");
 28                  var ele=document.createElement("span");
 29                  ele.innerHTML=mark+"不能为空!";
 30                  $(this).after(ele);
 31                  $(ele).prop("class","error");// DOM对象转换为jquery对象
 32                  flag=false;
 33                  //  return false-------->引出$.each的return false注意点
 34             }
 35 
 36 
 37         });
 38 
 39         return flag
 40     }
 41                    //---------------------------------------------------------
 42 //---------------------------------------------------------
 43                    //---------------------------------------------------------
 44 
 45 
 46 
 47         function f(){
 48 
 49         for(var i=0;i<4;i++){
 50 
 51             if (i==2){
 52                 return
 53             }
 54             console.log(i)
 55         }
 56 
 57     }
 58     f();  // 这个例子大家应该不会有问题吧!!!
 59 //------------------------------------------
 60     li=[11,22,33,44];
 61     $.each(li,function(i,v){
 62 
 63         if (v==33){
 64                 return ;   //  ===试一试 return false会怎样?
 65             }
 66             console.log(v)
 67     });
 68 
 69 //------------------------------------------
 70 
 71     //  $.MyEach(obj,function(i,v){}):
 72          for(var i in obj){
 73 
 74              func(i,obj[i]) ; //  i就是索引,v就是对应值
 75              // {}:我们写的大括号的内容就是func的执行语句;
 76          }
 77 
 78     // 大家再考虑: function里的return只是结束了当前的函数,并不会影响后面函数的执行
 79 
 80     //本来这样没问题,但因为我们的需求里有很多这样的情况:我们不管循环到第几个函数时,一旦return了,
 81     //希望后面的函数也不再执行了!基于此,jquery在$.each里又加了一步:
 82          for(var i in obj){
 83 
 84              ret=func(i,obj[i]) ;
 85              if(ret==false){
 86                  return ;
 87              }
 88 
 89          }
 90     // 这样就很灵活了:
 91     // <1>如果你想return后下面循环函数继续执行,那么就直接写return或return true
 92     // <2>如果你不想return后下面循环函数继续执行,那么就直接写return false
 93 
 94 
 95 // ---------------------------------------------------------------------
 96    // 说了这么多,请问大家如果我们的需求是:判断出一个输入有问题后面就不判断了(当然也就不显示了),
 97    // 怎么办呢?
 98    // 对了
 99     if (value.trim().length==0){
100                   //...
101                   //...
102                   //flag=false;  //   flag=false不要去,它的功能是最后如果有问题,不提交数据!
103                   return false
104             }
105 
106 
107 //最后,大家尝试着用jquery的绑定来完成这个功能!
108 
109       $(".Form :submit").click(function(){});
110     
111 </script>
View Code

参考:http://www.cnblogs.com/xcj26/p/3345556.html 

原文地址:https://www.cnblogs.com/ltk-python/p/9513759.html