jQuery

参考手册:http://jquery.cuishifeng.cn/

模块 <==> 类库
DOM/BOM/JavaScript的类库

版本:
  1.X 目前所使用的均为1.X版本系列。
  2.X
  3.X

jQuery对象具有jQuery的属性方法,可以通过jQuery对象.attribute调用,另外还可以与Dom对象直接进行转换。
转换:
  jQuery对象通过 --jQuery对象[0] --转换为--> Dom对象
  Dom对象通过 --$(Dom对象) --转换为-->jQuery对象

一、查找元素

  DOM:10个左右;
  jQuery:选择器,筛选
    1.1 jQuery选择器:直接找到某个或某类标签
      1.1.1 基本选择器
        a. id选择器
          $('#id')
        b. class选择器
          $('.class')
        c. 标签选择器
          $('a') 找到所有的a标签
        d. *选择器 全选,找到页面上的所有标签
          $("*")
        e. 组合选择器selector1,selector2,selectorN
          $('a,.class,#id') 将所有的相关的标签都找到
      1.1.2 层级选择器
        $('div a') 在给定的祖先元素下匹配所有的后代元素,ancestor descendant ==> 子子孙孙
        $('div>a') 在给定的父元素下匹配所有的子元素,parent > child; ==> 仅找儿子
        $('div+a') 匹配所有紧接在 prev 元素后的 next 元素,prev + next ==>
        $('div~a') 匹配 prev 元素之后的所有 siblings 元素,prev ~ siblings ==>仅找兄弟
      1.1.3 基本筛选器
        :first 获取第一个元素 $('li:first');
        :last() 获取最后个元素 $('li:last');
        :eq(index) 匹配一个给定索引值的元素,索引从0开始 $("tr:eq(1)")查找第二行;

      1.1.4 内容
        :contains(text) 匹配包含给定文本的元素 $("div:contains('John')")
        :empty 匹配所有不包含子元素或者文本的空元素 $("td:empty")
        :has(selector) 匹配含有选择器所匹配的元素的元素 $("div:has(p)").addClass("test");
        :parent 匹配含有子元素或者文本的元素 $("td:parent")
      1.1.5 可见性
        :hidden 匹配所有不可见元素,或者type为hidden的元素 $("input:hidden")
        :visible 匹配所有的可见元素 $("tr:visible")
      1.1.6 属性---Important!!!()
        [attribute]
        [attribute=value]
        [attribute!=value]
        [attribute^=value]
        [attribute$=value]
        [attribute*=value]
        [attrSel1][attrSel2][attrSelN]
                    $('[alex]') 具有alex属性的所有标签
                    $('[alex="123"]') alex属性等于123的标签

1 <input type='text'/>
2 <input type='text'/>
3 <input type='file'/>
4 <input type='password'/>
5 
6 $("input[type='text']")
7 $(':text')  //两种选择器的实现结果等价
View Code

                  

    1.2 jQuery筛选器:
      筛选器:查找
        $(this).next() 下一个同辈元素
        $(this).nextAll() 查找当前元素之后所有的同辈元素。
        $(this).nextUntil() 查找当前元素之后所有的同辈元素,直到遇到匹配的那个元素为止。
        $(this).prev() 上一个
        $(this).parent() 父
        $(this).parents() 父亲及祖宗们
        $(this).children() 孩子
        $('#i1').siblings() 兄弟
        $('#i1').find('#i1') 子子孙孙中查找
      筛选器:过滤
        $(this).eq(1) 获取当前链式操作中第N个jQuery对象,返回jQuery对象,当参数大于等于0时为正向选取,比如0代表第一个,1代表第二个。当参数为负数时为反向选取,比如-1为倒数第一个.类似的有get(index),不过get(index)返回的是DOM对象。
        $(this).first() 获取第一个元素
        $(this).last() 获取最后一个元素
        $(this).hasClass() 检查当前的元素是否含有某个特定的类,如果有,则返回true。


二、操作元素
  文本操作
    $(..).text() 获取文本内容
    $(..).text('<a>123</a>') 设置文本内容
    $(..).html() 获取第一个匹配元素的html内容。
    $(..).html('<a>123</a>') 设置第一个匹配元素的html内容。
    $(..).val() 获取value值
    $(..).val('') 设置value值为''(空)

  样式操作
    $('.i1').addClass('hide') 添加样式
    $('#i1').removeClass('hide') 移除样式
    $('#i1').toggleClass('hide') 如果存在(不存在)就删除(添加)一个类。
      等价于:
      if($('.c1').hasClass('hide')){
        $('.c1').removeClass('hide');
      }else{
        $('.c1').addClass('hide');
      }

  属性操作
    $(..).attr 设置或返回被选元素的属性值。专门用于做自定义属性。
    $(..).attr('value') 返回被选元素的指定属性值
    $(..).attr('value','val1') 设置元素的指定属性值
    $(..).removeAttr('value') 删除被选元素的指定属性值
    $(..).prop 获取在匹配的元素集中的第一个元素的属性值。专门用于checkbox,radio。
    $(..).prop('checked',true)
    $(..).prop('checked',false)

    ps:
      index 获取索引位置

  文档处理
    append
    prepend
    after
    before

    remove
    empty

    clone

    实例参考: 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <div style="margin:0 auto;">
 9         <input class='t1' type="text"/>
10         <input class="a1" type="button" value="添加"/>
11         <input class="a2" type="button" value="删除"/>
12         <input class="a3" type="button" value="复制"/>
13 
14     </div>
15     <div>
16         <ul>
17             <li>1</li>
18             <li>2</li>
19         </ul>
20     </div>
21     <script src="jquery-1.12.4.js"></script>
22     <script>
23     $(".a1").click(function(){
24         var text=$(".t1").val();
25         $("ul").append("<li>"+text+"</li>");
26     })
27 
28     $('.a2').click(function(){
29         var index=$('.t1').val();
30 //        $("ul").children().eq(index).empty();  //不清空标签,仅清空值
31         $("ul").children().eq(index).remove();
32     })
33 
34     $('.a3').click(function(){
35          var index=$('.t1').val();
36          var v1=$("ul").children().eq(index).clone()
37          $("ul").append(v1)
38 
39     })
40     </script>
41 </body>
42 </html>
View Code

  css处理
    $("t1").css("样式名称","样式值")
    点赞效果:
      - $("t1").append()
      - $("t1").remove()
      - setInterval
      - 透明度opacity 1==>0
      - position(relative,absolute) top right
      - fontsize字体大小

  位置
    $(window).scrollTop() 获取匹配元素相对滚动条顶部的偏移。
    $(window).scrollTop(100) 设置相对滚动条顶部的偏移

    offset 指定标签在html中的坐标
      $("#i1").offset()
        {top: 8, left: 8}
      $("#i1").offset().left 获取指定标签在html中的坐标值

    position 指定标签相对父标签(relative)标签的坐标

  尺寸
    $("i1").height() 获取标签的高度 纯高度。取得匹配元素当前计算的高度值(px)。
    $("i1").innerHeight() 获取第一个匹配元素内部区域高度(包括补白、不包括边框)
    $("i1").outerHeight() 获取第一个匹配元素外部高度(默认包括补白和边框)。默认值:'false'
    $("i1").outerHeight(true) 获取第一个匹配元素外部高度(默认包括补白和边框)。设置为 true 时,计算边距在内。

  事件
    DOM:三种绑定方式
    jQuery:
        $(".c1").click()

        $(".c1").bind("click",function(){})
        $(".c1").unbind("click",function(){})

      事件委派
        $(".c1").delegate("a",click",function(){})
        $(".c1").undelegate("a",click",function(){})

      事件处理
        $(".c1").on("click",function(){})
        $(".c1").off("click",function(){})

      阻止事件发生
        return false

 1 // 对于阻止事件发生的DOM和jQuery的绑定方式。
 2 // 第一种:DOM的绑定方式:
 3 <a onclick="return Func();">click here!</a>
 4 <script>
 5     function Func(){
 6         return false 7     }    
 8 </script>
 9 
10 //第二种:jQuery的绑定方式:
11 <a>click here!</a>
12 <script>
13     $("a").click(function(){
14         return false15     })    
16 </script>
View Code

      #单页面框架加载完成之后,自动执行
        $(function(){
          $(...)
        })

      不加$(function(){...})的写法,当页面所有元素完全加载完毕后,再执行。

      jQuery扩展:
        - $.extend $.方法名
        - $.fn.extend $(..).方法名

        为了防止不同的jQuery拓展中的全局变量名称重复,用自执行函数来封装。并将其中的全局变量变为局部变量,仅在在自执行函数内的生效。
        (function(){
          var status = 1;
          // 封装变量
        })(jQuery)

三、操作实例

实例1:全选取消反选

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <div>
 9         <input type="button" value="全选" onclick="chooseAll()"/>
10         <input type="button" value="反选" onclick="reverseAll()"/>
11         <input type="button" value="取消" onclick="cancelAll()"/>
12 
13     </div>
14     <table border="1">
15         <thead>
16             <th>选项</th>
17             <th>IP</th>
18             <th>PORT</th>
19         </thead>
20         <tbody>
21             <tr><td><input type="checkbox"/></td><td>1.1.1.1</td><td>80</td></tr>
22             <tr><td><input type="checkbox"/></td><td>1.1.1.1</td><td>80</td></tr>
23             <tr><td><input type="checkbox"/></td><td>1.1.1.1</td><td>80</td></tr>
24         </tbody>
25     </table>
26     <script src="jquery-1.12.4.js"></script>
27     <script>
28         function chooseAll(){
29             $('td :checkbox').prop('checked',true)
30         }
31         function cancelAll(){
32             $('td :checkbox').prop('checked',false)
33         }
34         function reverseAll(){
35             $('td :checkbox').each(function (k){
36                 var v = $(this).prop('checked')?false:true;
37                 $(this).prop('checked',v);})
38         }
39 
40     </script>
41 
42 </body>
43 </html>
View Code

上述实例的JS代码部分,如果使用DOM的原生写法:

 1 function reverseAll() {
 2             $(':checkbox').each(function(k){
 3                 // this,代指当前循环的每一个元素
 4                 // Dom            
 5                 if(this.checked){
 6                     this.checked = false;
 7                 }else{
 8                     this.checked = true;
 9                 } 
10             })
11         }
View Code

如果使用jquery的写法二:

 1  function reverseAll() {
 2             $(':checkbox').each(function(k){
 3                 // this,代指当前循环的每一个元素
 4                 if($(this).prop('checked')){
 5                     $(this).prop('checked', false);
 6                 }else{
 7                     $(this).prop('checked', true);
 8                 }
 9             })
10         }
View Code

总结:
  多选,反选,全选

      - 选择权
      -
        $('td :checkbox').prop('checked'); 获取值
        $('td :checkbox').prop('checked', true); 设置值
      -
        jQuery方法内置循环: $('td :checkbox').xxxx

      - $('td :checkbox').each(function(k){
        // k当前索引
        // this,DOM,当前循环的元素 $(this)

       })
      - var v = 条件 ? 真值 : 假值

实例2:后台管理界面左侧菜单收缩展开

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         .header{
 8             background-color: darkblue;
 9         }
10         .content{
11             background-color: #2459a2;
12             min-hight:50px;
13         }
14         .hide{
15             display:None
16         }
17     </style>
18 </head>
19 <body>
20     <div style="height:400px;200px;">
21         <div class="item">
22             <div class="header">标题1</div>
23             <div class="content">内容11</div>
24             <div class="content">内容12</div>
25             <div class="content">内容13</div>
26         </div>
27         <div class="item">
28             <div class="header">标题2</div>
29             <div class="content hide">内容21</div>
30             <div class="content hide">内容22</div>
31             <div class="content hide">内容23</div>
32         </div>
33         <div class="item">
34             <div class="header">标题3</div>
35             <div class="content hide">内容31</div>
36             <div class="content hide">内容32</div>
37             <div class="content hide">内容33</div>
38         </div>
39         <div class="item">
40             <div class="header">标题4</div>
41             <div class="content hide">内容41</div>
42             <div class="content hide">内容42</div>
43             <div class="content hide">内容43</div>
44 
45         </div>
46     </div>
47     <script src="jquery-1.12.4.js"></script>
48     <script>
49         $('.header').click(function () {
50             $(this).nextAll().removeClass('hide').parent().siblings().find('.content').addClass('hide');
51         })  // 会帮所有找到的jQuery对象循环click事件
52 
53     </script>
54 
55 </body>
56 </html>
View Code

总结:
  筛选器:查找
    $(this).next() 下一个同辈元素
    $(this).nextAll() 查找当前元素之后所有的同辈元素。
    $(this).nextUntil() 查找当前元素之后所有的同辈元素,直到遇到匹配的那个元素为止。
    $(this).prev() 上一个
    $(this).parent() 父
    $(this).parents() 父亲及祖宗们
    $(this).children() 孩子
    $('#i1').siblings() 兄弟
    $('#i1').find('#i1') 子子孙孙中查找
  筛选器:过滤
    $(this).eq(1) 获取当前链式操作中第N个jQuery对象,返回jQuery对象,当参数大于等于0时为正向选取,比如0代表第一个,1代表第二个。当参数为负数时为反向选取,比如-1为倒数第一个.类似的有get(index),不过get(index)返回的是DOM对象。
    $(this).first() 获取第一个元素
    $(this).last() 获取最后一个元素
    $(this).hasClass() 检查当前的元素是否含有某个特定的类,如果有,则返回true。

  链式编程
    $(...).click(function(){
    $(this).nextAll().removeClass('hide').parent().siblings().find('.content').addClass('hide')
    // 等价于 $(this).nextAll().removeClass('hide'); $(this).parent().siblings().find('.content').addClass('hide')
    })


  jQuery绑定事件
    $('.i1').click(function(){}) 为jQuery对象自动循环添加click事件

  改变样式
    $('.i1').addClass('hide') 添加样式
    $('#i1').removeClass('hide') 移除样式


实例3:模态对话框

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <style>
  7         .hide{
  8             display: none;
  9         }
 10         .modal{
 11             position: fixed;
 12             top: 50%;
 13             left: 50%;
 14             width: 500px;
 15             height: 400px;
 16             margin-left: -250px;
 17             margin-top: -250px;
 18             background-color: #eeeeee;
 19             z-index: 10;
 20         }
 21         .shadow{
 22             position: fixed;
 23             top: 0;
 24             left: 0;
 25             right: 0;
 26             bottom: 0;
 27             opacity: 0.6;
 28             background-color: black;
 29             z-index: 9;
 30         }
 31     </style>
 32 </head>
 33 <body>
 34     <a onclick="addElement();">添加</a>
 35 
 36     <table border="1" id="tb">
 37         <tr>
 38             <td target="hostname">1.1.1.11</td>
 39             <td target="port">80</td>
 40             <td target="ip">80</td>
 41             <td>
 42                 <a class="edit">编辑</a> | <a class="del">删除</a>
 43             </td>
 44         </tr>
 45         <tr>
 46             <td target="hostname">1.1.1.12</td>
 47             <td target="port">80</td>
 48             <td target="ip">80</td>
 49             <td>
 50                 <a class="edit">编辑</a> | <a class="del">删除</a>
 51             </td>
 52         </tr>
 53         <tr>
 54             <td target="hostname">1.1.1.13</td>
 55             <td target="port">80</td>
 56             <td target="ip">80</td>
 57             <td>
 58                 <a class="edit">编辑</a> | <a class="del">删除</a>
 59             </td>
 60         </tr>
 61         <tr>
 62             <td target="hostname">1.1.1.14</td>
 63             <td target="port">80</td>
 64             <td target="ip">80</td>
 65             <td>
 66                 <a class="edit">编辑</a> | <a class="del">删除</a>
 67             </td>
 68 
 69         </tr>
 70     </table>
 71 
 72     <div class="modal hide">
 73         <div>
 74             <input name="hostname" type="text"  />
 75             <input name="port" type="text" />
 76             <input name="ip" type="text" />
 77         </div>
 78 
 79         <div>
 80             <input type="button" value="取消" onclick="cancelModal();" />
 81             <input type="button" value="确定" onclick="confirmModal();" />
 82         </div>
 83     </div>
 84 
 85     <div class="shadow hide"></div>
 86 
 87     <script src="jquery-1.12.4.js"></script>
 88     <script>
 89 
 90         $('.del').click(function () {
 91             $(this).parent().parent().remove();
 92         });
 93         
 94         function  confirmModal() {
 95 
 96             var tr = document.createElement('tr');
 97             var td1 = document.createElement('td');
 98             td1.innerHTML = "11.11.11.11";
 99             var td2 = document.createElement('td');
100             td2.innerHTML = "8001";
101 
102             $(tr).append(td1);
103             $(tr).append(td2);
104 
105             $('#tb').append(tr);
106 
107             $(".modal,.shadow").addClass('hide');
108 //            $('.modal input[type="text"]').each(function () {
109 //                // var temp = "<td>..."
110 //
111 //
112 //
113 //            })
114         }
115 
116         function  addElement() {
117             $(".modal,.shadow").removeClass('hide');
118         }
119         function cancelModal() {
120             $(".modal,.shadow").addClass('hide');
121             $('.modal input[type="text"]').val("");
122         }
123 
124         $('.edit').click(function(){
125             $(".modal,.shadow").removeClass('hide');
126             // this
127             var tds = $(this).parent().prevAll();
128             tds.each(function () {
129                 // 获取td的target属性值
130                 var n = $(this).attr('target');
131                 // 获取td中的内容
132                 var text = $(this).text();
133                 var a1 = '.modal input[name="';
134                 var a2 = '"]';
135                 var temp = a1 + n + a2;
136                 $(temp).val(text);
137             });
138 
139 
140 //            var port = $(tds[0]).text();
141 //            var host = $(tds[1]).text();
142 //
143 //            $('.modal input[name="hostname"]').val(host);
144 //            $('.modal input[name="port"]').val(port);
145             // 循环获取tds中内容
146             // 获取 <td>内容</td> 获取中间的内容
147             // 赋值给input标签中的value
148 
149         });
150     </script>
151 </body>
152 </html>
View Code

实例4:TAB菜单切换

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         .menu{
 8             height: 38px;
 9             background-color: #eeeeee;
10             line-height: 38px;
11         }
12         .menu-item{
13             float:left;
14             border-right: 1px solid red;
15             padding: 0 5px;
16             cursor: pointer;
17         }
18         .hide{
19             display:None;
20         }
21         .active{
22             background-color: brown;
23         }
24         .content{
25             min-height: 100px;
26             border: 1px solid #eeeeee;
27         }
28     </style>
29 </head>
30 <body>
31     <div style=" 700px;margin:0 auto">
32         <div class="menu">
33             <div class="menu-item active">菜单一</div>
34             <div class="menu-item">菜单二</div>
35             <div class="menu-item">菜单三</div>
36         </div>
37         <div class="content">
38             <div>内容一</div>
39             <div>内容二</div>
40             <div>内容三</div>
41         </div>
42     </div>
43     <script src="jquery-1.12.4.js"></script>
44     <script>
45         $(".menu-item").click(function(){
46             $(this).addClass('active').siblings().removeClass('active');
47             $(".content").children().eq($(this).index()).removeClass('hide').siblings().addClass('hide');
48         })
49     </script>
50 </body>
51 </html>
View Code


实例5:点赞动态效果

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         .container{
 8             border:1px solid #dddddd;
 9             padding:50px;
10         }
11         .item{
12             position:relative;
13         }
14     </style>
15 </head>
16 <body>
17     <div class="container">
18         <span class="item"></span>
19     </div>
20     <div class="container">
21         <span class="item"></span>
22     </div>
23     <div class="container">
24         <span class="item"></span>
25     </div>
26     <div class="container">
27         <span class="item"></span>
28     </div>
29     <script src="jquery-1.12.4.js"></script>
30     <script>
31         $(".item").click(function(){
32             addFavor($(this));
33         })
34         function addFavor(self){
35             var tag=document.createElement('span');
36             $(tag).text("+1");
37             var fontsize=15;
38             var top=0;
39             var right=0;
40             var opacity=1;
41 
42             $(tag).css("position","absolute");
43             $(tag).css('color','green');
44             $(tag).css("fontsize",fontsize+"px");
45             $(tag).css("top",top+"px");
46             $(tag).css("right",right+"px");
47             $(tag).css("opacity",opacity);
48 
49             self.append(tag);
50 
51             var obj=setInterval(function(){
52                 fontsize=fontsize+10;
53                 top=top-10;
54                 right=right-10;
55                 opacity=opacity-0.1;
56                 $(tag).css('fontSize',fontsize + "px");
57                 $(tag).css('right',right + "px");
58                 $(tag).css('top',top + 'px');
59                 $(tag).css('opacity',opacity);
60                 if(opacity<0){
61                     console.log("obj",obj);
62                     clearInterval(obj);
63                     $(tag).remove();
64                 }
65             },40)
66         }
67 
68 
69     </script>
70 
71 </body>
72 </html>
View Code
原文地址:https://www.cnblogs.com/zoe233/p/7559966.html