zoukankan      html  css  js  c++  java
  • 前端基础之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 里的方法:

    jquery对象和DOM对象

    1、jQuery对象是一个数组对象,可以通过[index]的方法得到相应的DOM对象。

    var $cr = $("#cr"); //jQuery对象
    var cr = $cr[0] //DOM对象
    alert(cr.checked) //检测这个checkbox是否选中了

    2、通过get(index)方法得到相应的DOM对象。

    var $cr = $("#cr");
    var cr = $cr.get(0);
    alert(cr.checked);

    对于一个DOM对象,只需要用$()把DOM对象包装起来,就可以获得一个jQuery对象了,方式为$(DOM对象)。

    var cr = document.getElementByID("cr"); //DOM对象
    var $cr = $(cr);
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div class="dv">
        <span>好好学习天天向上</span>
    </div>
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        //Dom对象操作
        var dv1=document.getElementsByClassName("dv")[0];
        console.log(dv1.innerHTML);
        console.log(dv1.innerText);
        //jquery对象
        var dv2= $(".dv");
        console.log(dv2.html());
        console.log(dv2.text());
    
    
        //dom对象转换为jQuery对象只需要在dom对象前面加“$”
        var s=$("dv1");
        console.log(s.html());
        console.log(s.text());
    
        //jQuery对象转换Weidom对象只需要对jqery对象取索引或者jquery对象.get(索引值)
    
        var doms1=dv2[0];
        console.log(doms1.innerHTML);
        console.log(doms1.innerText);
    
    
        var doms2=dv2.get(0);
        console.log(doms2.innerHTML)
        console.log(doms2.innerText)
    </script>
    </html>

    三 选择器和筛选器

    1.基本选择器:

    - ID选择器              $("#id的值")
    - 类选择器(class)      $(".class的值")
    - 标签选择器(html标签)   $("标签的名字")
    - 所有标签              $("*")
    - 组合选择器             $("xx,xxx")

    2.层级选择器

                - 从一个标签的子子孙孙去找   $("父亲 子子孙孙") 
                - 从一个标签的儿子里面找     $("父亲>儿子标签")
                - 找紧挨着的标签             $("标签+下面紧挨着的那个标签")
                - 找后面所有同级的           $("标签~寻找同级的标签名")

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

    3基本筛选器

    :first    $("p:first")    第一个 <p> 元素
    :last    $("p:last")    最后一个 <p> 元素
    :even    $("tr:even")    所有偶数 <tr> 元素,索引值从 0 开始,第一个元素是偶数 (0),第二个元素是奇数 (1),以此类推。
    :odd    $("tr:odd")    所有奇数 <tr> 元素,索引值从 0 开始,第一个元素是偶数 (0),第二个元素是奇数 (1),以此类推。

    :eq(index)    $("ul li:eq(3)")    列表中的第四个元素(index 值从 0 开始)
    :gt(no)    $("ul li:gt(3)")    列举 index 大于 3 的元素
    :lt(no)    $("ul li:lt(3)")    列举 index 小于 3 的元素
    :not(selector)    $("input:not(:empty)")    所有不为空的输入元素
    :header    $(":header")    所有标题元素 <h1>, <h2> ...
    :animated    $(":animated")    所有动画元素
    :focus    $(":focus")    当前具有焦点的元素

    4内容筛选器

    :contains(text)    $(":contains('Hello')")    所有包含文本 "Hello" 的元素
    :has(selector)    $("div:has(p)")    所有包含有 <p> 元素在其内的 <div> 元素
    :empty    $(":empty")    所有空元素
    :parent    $(":parent")    匹配含有子元素或者文本的元素

    5 可见性

    :hidden    $("p:hidden")    所有隐藏的 <p> 元素
    :visible    $("table:visible")    所有可见的表格

    6属性

    [attribute]    $("[href]")    所有带有 href 属性的元素
    [attribute=value]    $("[href='default.htm']")    所有带有 href 属性且值等于 "default.htm" 的元素
    [attribute!=value]    $("[href!='default.htm']")    所有带有 href 属性且值不等于 "default.htm" 的元素
    [attribute$=value]    $("[href$='.jpg']")    所有带有 href 属性且值以 ".jpg" 结尾的元素
    [attribute|=value]    $("[title|='Tomorrow']")    所有带有 title 属性且值等于 'Tomorrow' 或者以 'Tomorrow' 后跟连接符作为开头的字符串
    [attribute^=value]    $("[title^='Tom']")    所有带有 title 属性且值以 "Tom" 开头的元素
    [attribute~=value]    $("[title~='hello']")    所有带有 title 属性且值包含单词 "hello" 的元素
    [attribute*=value]    $("[title*='hello']")    所有带有 title 属性且值包含字符串 "hello" 的元素
    [name=value][name2=value2]    $( "input[id][name$='man']" )    带有 id 属性,并且 name 属性以 man 结尾的输入框

    7 表单

    :input    $(":input")    所有 input 元素
    :text    $(":text")    所有带有 type="text" 的 input 元素
    :password    $(":password")    所有带有 type="password" 的 input 元素
    :radio    $(":radio")    所有带有 type="radio" 的 input 元素
    :checkbox    $(":checkbox")    所有带有 type="checkbox" 的 input 元素
    :submit    $(":submit")    所有带有 type="submit" 的 input 元素
    :reset    $(":reset")    所有带有 type="reset" 的 input 元素
    :button    $(":button")    所有带有 type="button" 的 input 元素
    :image    $(":image")    所有带有 type="image" 的 input 元素
    :file    $(":file")    所有带有 type="file" 的 input 元素

    8表单对象属性

    :enabled    $(":enabled")    所有启用的元素
    :disabled    $(":disabled")    所有禁用的元素
    :selected    $(":selected")    所有选定的下拉列表元素
    :checked    $(":checked")    所有选中的复选框选项

    四 筛选

    4.1  过滤

    eq()    返回带有被选元素的指定索引号的元素
    first()    返回被选元素的第一个元素
    last()    返回被选元素的最后一个元素
    has()    返回拥有一个或多个元素在其内的所有元素
    hasClass(class) 检查当前的元素是否含有某个特定的类,如果有,则返回true。
    slice() 把匹配元素集合缩减为指定范围的子集
    not()
    从匹配元素的集合中删除与指定表达式匹配的元素

    4.2 查find() 返回被选元素的后代元素

    children()    返回被选元素的所有直接子元素
    closest()    返回被选元素的第一个祖先元素
    contents()    返回被选元素的所有直接子元素(包含文本和注释节点)
    next()    返回被选元素的后一个同级元素
    nextAll()    返回被选元素之后的所有同级元素
    nextUntil()    返回介于两个给定参数之间的每个元素之后的所有同级元素
    parent()    返回被选元素的直接父元素
    parents()    返回被选元素的所有祖先元素
    parentsUntil()    返回介于两个给定参数之间的所有祖先元素
    prev()    返回被选元素的前一个同级元素
    prevAll()    返回被选元素之前的所有同级元素
    prevUntil()    返回介于两个给定参数之间的每个元素之前的所有同级元素
    slibings()   返回被选元素的所有同级元素

    五 属性操作

      5.1 属性

       

     1.attr( name | pro | key,val |fn )读取或修改元素的属性值(行内)。

    参数:
    1.name:属性的名称。(用于读取值)
    2.properties:作为属性的名称的对象。(用于修改多个属性)
    3.key,value:属性名和属性值.(用于修改多个属性)
    4.fn:回调函数。function(index,attr){}。index为元素队列中的索引值,attr为元素原来的属性值。

    $("img").attr("src");
    
    $("img").attr({ src: "test.jpg", alt: "Test Image" });
    
    $("img").attr("src","test.jpg");
    
    $("img").attr("title", function() { return this.src });

    2.removeAttr( name )

    移除属性。

    参数:name。属性名称。

    1 $("img").removeAttr("src");

    3.prop(n | p | k,v | f )

    读取或修改属性。该方法与attr方法类似,但该方法针对布尔类型的属性。

    $("input[type='checkbox']").prop("checked");
    $("input[type='checkbox']").prop({
      disabled: true
    });
    
    $("input[type='checkbox']").prop("checked", function( i, val ) {
      return !val;
    });

    4.removeProp(name)

    移除属性。该方法所移除的属性不推荐默认属性。

    1 var $para = $("p");
    2 $para.prop("luggageCode", 1234);
    3 $para.append("The secret luggage code is: ", String($para.prop("luggageCode")), ". ");
    4 $para.removeProp("luggageCode");
    5 $para.append("Now the secret luggage code is: ", String($para.prop("luggageCode")), ". ");
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            img{
                width: 600px;
                height:500px;
            }
        </style>
    </head>
    <body>
    <img src="1.png" alt="meinv" data-src="3.png">
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        $("img").on("click",function () {
            var img=$(this).attr("data-src");
            $(this).attr("src",img);
        });
    </script>
    </html>
    点击加载图片
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>全选取消反选</title>
        <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
    </head>
    <body>
    
    <div class="container">
        <div class="row">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <button id="all" class="btn btn-info">全选</button>
                    <button id="cancel" class="btn btn-info">取消</button>
                    <button id="reverse" class="btn btn-info">反选</button>
                </div>
                <div class="panel-body">
                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Username</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <th scope="row"><input type="checkbox"></th>
                            <td>Mark</td>
                            <td>Otto</td>
                            <td>@mdo</td>
                        </tr>
                        <tr>
                            <th scope="row"><input type="checkbox"></th>
                            <td>Jacob</td>
                            <td>Thornton</td>
                            <td>@fat</td>
                        </tr>
                        <tr>
                            <th scope="row"><input type="checkbox"></th>
                            <td>Larry</td>
                            <td>the Bird</td>
                            <td>@twitter</td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        $("#all").on("click",function () {
            $(":checkbox").prop("checked",true);
        });
    
         $("#cancel").on("click",function () {
            $(":checkbox").prop("checked",false);
        });
    
         $("#reverse").on("click",function () {
            var check=$(":checkbox");
    
             check.each(function () {
                 var ischeck=$(this).prop("checked");
                $(this).prop("checked",!ischeck) ;
             })
        })
    </script>
    </html>
    全选反选取消

    5.2 css 类

    addClass(class) — 为每个匹配的元素添加指定的类名。
    参数 : class — 一个或多个要添加到元素中的CSS类名,请用空格分开(String)
    示例 一 :
    为匹配的元素加上 'selected' 类
    HTML 代码:
    <p>Hello</p>
    jQuery 代码:
    $("p").addClass("selected");
    结果:
    [ <p class="selected">Hello</p> ]
    示例 二 :
    为匹配的元素加上 selected highlight 类
    HTML 代码:
    <p>Hello</p>
    jQuery 代码:
    $("p").addClass("selected highlight");
    结果:
    [ <p class="selected highlight">Hello</p> ]

    addClass(function(index, class)) — 为每个匹配的元素添加指定的类名。

    参数 : function(index, class) — 此函数必须返回一个或多个空格分隔的class名。接受两个参数,index参数为对象在这个集合中的索引值,class参数为这个对象原先的class属性值。(Function)
    示例 : 给li加上不同的class
    HTML 代码:
    <ul><li>Hello</li><li>Hello</li><li>Hello</li></ul>
    jQuery 代码:
    $('ul li:last').addClass(function() {
      return 'item-' + $(this).index();
    });

    removeClass([class]) — 从所有匹配的元素中删除全部或者指定的类。

    参数 : class (可选) — 一个或多个要删除的CSS类名,请用空格分开(String)
    示例 : 
    从匹配的元素中删除 'selected' 类
    HTML 代码:
    <p class="selected first">Hello</p>
    jQuery 代码:
    $("p").removeClass("selected");
    结果:
    [ <p class="first">Hello</p> ]

    删除匹配元素的所有类
    HTML 代码:
    <p class="selected first">Hello</p>
    jQuery 代码:
    $("p").removeClass();
    结果:
    [ <p>Hello</p> ]

    removeClass(function(index, class)) — 从所有匹配的元素中删除全部或者指定的类。
    参数 : function(index, class) — 此函数必须返回一个或多个空格分隔的class名。接受两个参数,index参数为对象在这个集合中的索引值,class参数为这个对象原先的class属性值。(Function)
    示例:
    删除最后一个元素上与前面重复的class
    jQuery 代码:
    $('li:last').removeClass(function() {
        return $(this).prev().attr('class');
    });

    toggleClass(class) — 如果存在(不存在)就删除(添加)一个类。
    参数 : class — CSS类名(String)
    示例 :
    为匹配的元素切换 'selected' 类
    HTML 代码:
    <p>Hello</p><p class="selected">Hello Again</p>
    jQuery 代码:
    $("p").toggleClass("selected");
    结果:
    [ <p class="selected">Hello</p>, <p>Hello Again</p> ]

    toggleClass(class, switch) — 如果开关switch参数为true则加上对应的class,否则就删除。
    参数 :
    class — 要切换的CSS类名(String)
    switch — 用于决定元素是否包含class的布尔值(Boolean)
    示例 :
    每点击三下加上一次 'highlight' 类
    HTML 代码:
    <strong>jQuery 代码:</strong>
    jQuery 代码:
      var count = 0;
      $("p").click(function(){
          $(this).toggleClass("highlight", count++ % 3 == 0);
      });

    toggleClass(function(index, class), [switch])— 如果开关switch参数为true则加上对应的class,否则就删除。
    参数 :
    function(index, class)— 返回class名的一个函数,接受两个参数,index为元素在集合中的索引位置,class为原先元素的class值(Function)
    switch — (可选)用于决定元素是否包含class的布尔值(Boolean)
    示例 :
    根据父元素来设置class属性
    jQuery 代码:
    $('div.foo').toggleClass(function() {
      if ($(this).parent().is('.bar') {
        return 'happy';
      } else {
        return 'sad';
      }
    });

     5.3 html 文本操作

    html([val|fn])

    取得第一个匹配元素的html内容。这个函数不能用于XML文档。但可以用于XHTML文档。

    在一个 HTML 文档中, 我们可以使用 .html() 方法来获取任意一个元素的内容。 如果选择器匹配多于一个的元素,那么只有第一个匹配元素的 HTML 内容会被获取。

    没有参数就是获取对应的值 有参数就是设置对应的值

    无参数 描述:
    返回p元素的内容。
    jQuery 代码:
    $('p').html();
    参数val 描述:
    设置所有 p 元素的内容
    jQuery 代码:
    $("p").html("Hello <b>world</b>!");
    回调函数描述:
    使用函数来设置所有匹配元素的内容。
    jQuery 代码:
    $("p").html(function(n){
        return "这个 p 元素的 index 是:" + n;
        });

      text([val|fn])

    取得所有匹配元素的内容。

    结果是由所有匹配元素包含的文本内容组合起来的文本。这个方法对HTML和XML文档都有效。

    无参数 描述:
    返回p元素的文本内容。
    jQuery 代码:
    $('p').text();
    参数val 描述:
    设置所有 p 元素的文本内容
    jQuery 代码:
    $("p").text("Hello world!");
    回调函数 描述:
    使用函数来设置所有匹配元素的文本内容。
    jQuery 代码:
    $("p").text(function(n){
        return "这个 p 元素的 index 是:" + n;
        });

    val([val|fn|arr]

    - input
    - 获取的是输入的内容

    - checkbox
    - 获取的是value值

    - select
    - 单选 就是获取值
    - 多选 得到的是一个数组,设置的时候也要是数组

    获得匹配元素的当前值。

    在 jQuery 1.2 中,可以返回任意元素的值了。包括select。如果多选,将返回一个数组,其包含所选的值。

    参数
    valStringV1.0
    要设置的值。
    function(index, value)FunctionV1.4
    此函数返回一个要设置的值。接受两个参数,index为元素在集合中的索引位置,text为原先的text值。
    arrayArray<String>V1.0
    用于 check/select 的值
    无参数 描述:
    获取文本框中的值
    jQuery 代码:
    $("input").val();
    参数val 描述:
    设定文本框的值
    jQuery 代码:
    $("input").val("hello world!");
    回调函数 描述:
    设定文本框的值
    jQuery 代码:
    $('input:text.items').val(function() {
      return this.value + ' ' + this.className;
    });
    参数array 描述:
    设定一个select和一个多选的select的值
    HTML 代码:
    <select id="single">
      <option>Single</option>
      <option>Single2</option>
    </select>
    <select id="multiple" multiple="multiple">
      <option selected="selected">Multiple</option>
      <option>Multiple2</option>
      <option selected="selected">Multiple3</option>
    </select><br/>
    <input type="checkbox" value="check1"/> check1
    <input type="checkbox" value="check2"/> check2
    <input type="radio" value="radio1"/> radio1
    <input type="radio" value="radio2"/> radio2
    jQuery 代码:
    $("#single").val("Single2");
    $("#multiple").val(["Multiple2", "Multiple3"]);
    $("input").val(["check2", "radio1"]);

    六 css 操作

     6.1 css

    .css()
            - .css("color")  -> 获取color css值
            - .css("color", "#ff0000") -> 设置值
            - .css({"color": "#cccccc", "border": "1px solid #ff0000"})  -> 设置多个值
            - .css(["color", "border"])  -> 获取多个值

    6.2 位置

    .offset
            - 获取相对位置
            - 比较的对象是 htm(既离屏幕的距离 top left)
         
        .position
            - 获取相对已经定位的父标签的位置
            - 比较的是最近的那个做过定位的祖先标签
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .dv1{
                width: 100px;
                height: 100px;
                background-color: red;
    
            }
            .dv{
                position: relative;
                top: 100px;
                left: 500px;
            }
            .dv2{
                 width: 100px;
                height: 100px;
                background-color: greenyellow;
                position: absolute;
                top: 100px;
                left: 100px;
            }
    
    
        </style>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
       <div class="dv">
           <div class="dv1"></div>
           <div class="dv2"></div>
       </div>
    
    </body>
    
    </html>
    /**
    $(".dv").offset()
    {top: 108, left: 508}
    $(".dv1").offset()
    {top: 108, left: 508}
    $(".dv2").offset()
    {top: 208, left: 608}
    $("dv").position()
    undefined
    $(".dv").position()
    {top: 108, left: 508}
    $(".dv1").position()
    {top: 0, left: 0}
    $(".dv2").position()
    {top: 100, left: 100}
    
    */
    绝对位置相对位置

    6.3 scroll

        scrollTop([val])
        
            - 返回顶部
            
        scrollLeft([val])
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .c1{
                height: 100px;
            }
            #dv{
                width: 100px;
                height: 40px;
                background-color: gray;
                line-height: 40px;
                text-align: center;
                position: fixed;
                bottom: 15px;
                right: 10px;
            }
            .hide{
                display: none;
            }
        </style>
    </head>
    <body>
    <div class="c1">1</div>
    <div class="c1">2</div>
    <div class="c1">3</div>
    <div class="c1">4</div>
    <div class="c1">5</div>
    <div class="c1">6</div>
    <div class="c1">7</div>
    <div class="c1">8</div>
    <div class="c1">9</div>
    <div class="c1">10</div>
    <div class="c1">11</div>
    <div class="c1">12</div>
    <div class="c1">13</div>
    <div class="c1">14</div>
    <div class="c1">15</div>
    <div class="c1">16</div>
    <div class="c1">17</div>
    <div class="c1">18</div>
    <div class="c1">19</div>
    <div class="c1">20</div>
    <div class="c1">21</div>
    <div class="c1">22</div>
    <div class="c1">23</div>
    <div class="c1">24</div>
    <div class="c1">25</div>
    <div class="c1">26</div>
    <div class="c1">27</div>
    <div class="c1">28</div>
    <div class="c1">29</div>
    <div class="c1">30</div>
    <div class="c1">31</div>
    <div class="c1">32</div>
    <div class="c1">33</div>
    <div class="c1">34</div>
    <div class="c1">35</div>
    <div class="c1">36</div>
    <div class="c1">37</div>
    <div class="c1">38</div>
    <div class="c1">39</div>
    <div class="c1">40</div>
    <div class="c1">41</div>
    <div class="c1">42</div>
    <div class="c1">43</div>
    <div class="c1">44</div>
    <div class="c1">45</div>
    <div class="c1">46</div>
    <div class="c1">47</div>
    <div class="c1">48</div>
    <div class="c1">49</div>
    <div class="c1">50</div>
    <div class="c1">51</div>
    <div class="c1">52</div>
    <div class="c1">53</div>
    <div class="c1">54</div>
    <div class="c1">55</div>
    <div class="c1">56</div>
    <div class="c1">57</div>
    <div class="c1">58</div>
    <div class="c1">59</div>
    <div class="c1">60</div>
    <div class="c1">61</div>
    <div class="c1">62</div>
    <div class="c1">63</div>
    <div class="c1">64</div>
    <div class="c1">65</div>
    <div class="c1">66</div>
    <div class="c1">67</div>
    <div class="c1">68</div>
    <div class="c1">69</div>
    <div class="c1">70</div>
    <div class="c1">71</div>
    <div class="c1">72</div>
    <div class="c1">73</div>
    <div class="c1">74</div>
    <div class="c1">75</div>
    <div class="c1">76</div>
    <div class="c1">77</div>
    <div class="c1">78</div>
    <div class="c1">79</div>
    <div class="c1">80</div>
    <div class="c1">81</div>
    <div class="c1">82</div>
    <div class="c1">83</div>
    <div class="c1">84</div>
    <div class="c1">85</div>
    <div class="c1">86</div>
    <div class="c1">87</div>
    <div class="c1">88</div>
    <div class="c1">89</div>
    <div class="c1">90</div>
    <div class="c1">91</div>
    <div class="c1">92</div>
    <div class="c1">93</div>
    <div class="c1">94</div>
    <div class="c1">95</div>
    <div class="c1">96</div>
    <div class="c1">97</div>
    <div class="c1">98</div>
    <div class="c1">99</div>
    <div class="c1">100</div>
    
    <div id="dv" class="hide">
        <a href="#">返回顶部</a>
    </div>
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        $(window).scroll(function () {
           if ($(window).scrollTop()>1000){
               $("#dv").removeClass("hide")
           }else{
              $("#dv").addClass("hide")
           }
       });
    
       $("#dv").on("click",function () {
           $(window).scrollTop(0);
       })
    </script>
    </html>
    返回顶部1
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <style>
        .dv{
            width: 100%;
            height: 4000px;
            background-color: greenyellow;
        }
        .dv1{
            width: 100px;
            height: 50px;
            text-align: center;
            line-height: 50px;
            background-color: gainsboro;
            color: white;
            text-decoration: none;
            position: fixed;
            bottom: 15px;
            right: 15px;
        }
        .dv1 a{
            color: beige;
            text-decoration: none;
        }
    
        .hide{
            display: none;
        }
    </style>
    <body>
    <div class="dv">
    
    </div>
    <div class="dv1 hide"><a href="#">返回顶部</a></div>
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        $(".dv1").on("click",function () {
           $(window).scrollTop(0);
        });
        $(window).scroll(function () {
             if($(window).scrollTop()>500) {
                 $(".dv1").removeClass("hide")
             }else {
                  $(".dv1").addClass("hide")
             }
        })
    </script>
    </html>

    6.4 尺寸

    height([val|fn])
            - 元素的高度
        width([val|fn])
        innerHeight()
            - 带padding的高度
        innerWidth()
        outerHeight([soptions])
            - 在innerHeight的基础上再加border的高度
        outerWidth([options])
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .dv{
                width: 300px;
                height: 300px;
                padding: 20px;
                border: 2px solid red;
                background-color: gainsboro;
            }
        </style>
    </head>
    <body>
     <div class="dv">
    
     </div>
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    </html>
    /*
    $(".dv").width()
    300
    $(".dv").height()
    300
    $(".dv").innerHeight()
    340
    $(".dv").innerWidth()
    340
    $(".dv").outerWidth()
    344
    $(".dv").outerHeight()
    344
    
    */
    尺寸

     七 文档操作

    内部插入(加粗)
        append(content|fn) --> 往后加
        appendTo(content)
        
        A.append(B)   -> 把B添加到A中元素的后面
        A.appendTo(B) -> 把A添加到B中元素的后面
        
        prepend(content|fn)  --> 往前加
        prependTo(content)
        
        A.prepend(B)   -> 把B添加到A中元素的前面
        A.prependTo(B) -> 把A添加到B中元素的前面
            
    外部插入(加粗)
        after(content|fn)   --> 往后加
        insertAfter(content)
        
        A.after(B)          --> 把B添加到A的后面
        A.insertAfter(B)    --> 把A添加到B的后面
        
        before(content|fn)   --> 往前加
        insertBefore(content)
        
        A.before(B)          --> 把B添加到A的前面
        A.insertBefore(B)     --> 把A添加到B的前面
        
        
        包裹
        wrap(html|ele|fn)
            A.wrap(B)  --> B包A
        unwrap()
            - 不要加参数
            
        wrapAll(html|ele)
        wrapInner(html|ele|fn)
        
        
        替换
        replaceWith(content|fn)
            A.replaceWith(B)  --> B替换A
            
        replaceAll(selector)
            A.replaceAll(B)   --> A替换B
        
        
        删除
        empty()
            - 清空 内部清空
        remove([expr])
            - 删除 整体都删除
        detach([expr])
            - 剪切  多保存在变量中,方便再次使用
            
        复制
        clone([Even[,deepEven]])
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <button class="btn">一刀999</button>
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        $(".btn").on("click",function () {
            $(this).clone(true).insertAfter($(this));
        })
    </script>
    </html>
    克隆

    八 动画

    基本
        show([s,[e],[fn]])
        hide([s,[e],[fn]])
        toggle([s],[e],[fn])
        
    滑动
        slideDown([s],[e],[fn])
        slideUp([s,[e],[fn]])
        slideToggle([s],[e],[fn])
        
    淡入淡出
        fadeIn([s],[e],[fn])
        fadeOut([s],[e],[fn])
        
        fadeTo([[s],o,[e],[fn]])
            - 淡出到0.66透明度
        fadeToggle([s,[e],[fn]])
            - .fadeToggle(3000, function () {
                alert("真没用3");
            });

    自定义
    animate(p,[s],[e],[fn])1.8*
    - css属性值都可以设置

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
                display: none;
            }
        </style>
    </head>
    <body>
    <button id="btn1">下滑</button>
    <button id="btn2">上拉</button>
    <button id="btn3">切换</button>
    <img  src="1.jpg" alt="" class="hide">
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
       $("#btn1").on("click",function () {
           $("img").slideDown(3000)
       })
    
        $("#btn2").on("click",function () {
            $("img").slideUp(3000)
        })
    
        $("#btn3").on("click",function () {
            $("img").slideToggle(1000,function () {
                alert(111)
            })
        })
    </script>
    </html>
    slide
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
                display: none;
            }
        </style>
    </head>
    <body>
    <button id="btn1">淡入</button>
    <button id="btn2">淡出</button>
    <button id="btn3">淡入淡出</button>
    <img  src="1.jpg" alt="" class="hide">
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
       $("#btn1").on("click",function () {
           $("img").fadeIn(3000)
       });
    
        $("#btn2").on("click",function () {
            $("img").fadeOut(3000)
        });
    
        $("#btn3").on("click",function () {
            $("img").fadeToggle(1000,function () {
                alert(111)
            })
        })
    </script>
    </html>
    fade
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <button class="btn">边框变小</button>
    <button class="btn2">切换</button>
    <img src="1.jpg" alt="">
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        $(".btn").on("click",function () {
            $("img").animate({
                100,
                height:100
            },3000,function () {
                alert(123)
            })
        })
    
    </script>
    </html>
    animate

     九 事件处理

     

    bind()    向匹配元素附加一个或更多事件处理器
    blur()    触发、或将函数绑定到指定元素的 blur 事件
    change()    触发、或将函数绑定到指定元素的 change 事件
    click()    触发、或将函数绑定到指定元素的 click 事件
    dblclick()    触发、或将函数绑定到指定元素的 double click 事件
    delegate()    向匹配元素的当前或未来的子元素附加一个或多个事件处理器
    die()    移除所有通过 live() 函数添加的事件处理程序。
    error()    触发、或将函数绑定到指定元素的 error 事件
    event.isDefaultPrevented()    返回 event 对象上是否调用了 event.preventDefault()。
    event.pageX    相对于文档左边缘的鼠标位置。
    event.pageY    相对于文档上边缘的鼠标位置。
    event.preventDefault()    阻止事件的默认动作。
    event.result    包含由被指定事件触发的事件处理器返回的最后一个值。
    event.target    触发该事件的 DOM 元素。
    event.timeStamp    该属性返回从 1970 年 1 月 1 日到事件发生时的毫秒数。
    event.type    描述事件的类型。
    event.which    指示按了哪个键或按钮。
    focus()    触发、或将函数绑定到指定元素的 focus 事件
    keydown()    触发、或将函数绑定到指定元素的 key down 事件
    keypress()    触发、或将函数绑定到指定元素的 key press 事件
    keyup()    触发、或将函数绑定到指定元素的 key up 事件
    live()    为当前或未来的匹配元素添加一个或多个事件处理器
    load()    触发、或将函数绑定到指定元素的 load 事件
    mousedown()    触发、或将函数绑定到指定元素的 mouse down 事件
    mouseenter()    触发、或将函数绑定到指定元素的 mouse enter 事件
    mouseleave()    触发、或将函数绑定到指定元素的 mouse leave 事件
    mousemove()    触发、或将函数绑定到指定元素的 mouse move 事件
    mouseout()    触发、或将函数绑定到指定元素的 mouse out 事件
    mouseover()    触发、或将函数绑定到指定元素的 mouse over 事件
    mouseup()    触发、或将函数绑定到指定元素的 mouse up 事件
    one()    向匹配元素添加事件处理器。每个元素只能触发一次该处理器。
    ready()    文档就绪事件(当 HTML 文档就绪可用时)
    resize()    触发、或将函数绑定到指定元素的 resize 事件
    scroll()    触发、或将函数绑定到指定元素的 scroll 事件
    select()    触发、或将函数绑定到指定元素的 select 事件
    submit()    触发、或将函数绑定到指定元素的 submit 事件
    toggle()    绑定两个或多个事件处理器函数,当发生轮流的 click 事件时执行。
    trigger()    所有匹配元素的指定事件
    triggerHandler()    第一个被匹配元素的指定事件
    unbind()    从匹配元素移除一个被添加的事件处理器
    undelegate()    从匹配元素移除一个被添加的事件处理器,现在或将来
    unload()    触发、或将函数绑定到指定元素的 unload 事件
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <input type="text" id="ip" value="请输入...">
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        var val=$("#ip").val();
        $("#ip ").focus(function () {
            $(this).val("");
        });
    
        $("#ip").blur(function () {
            $(this).val(val)
        });
    </script>
    </html>
    blur([[data],fn])
        
        focus([[data],fn])
            - 获取焦点
            - 搜索框例子
            
        change([[data],fn])
            - select
            
        click([[data],fn])
            - 点击
        
        dblclick([[data],fn])
            - 双击
    
        scroll([[data],fn])
            - 滚动
    
        submit([[data],fn])
            -提交
            
            
        补充:
            文档树加载完之后绑定事件(绝大部分情况下)
            $(document).ready(function(){
                // 绑定事件的代码
                ....
            })
            
            简写:
            $(function($){
                // 绑定事件的代码
                ....
            });
            

     十 事件委托(事件委派)

    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <hr>
    <button id="add_li">Add_li</button>
    <button id="off">off</button>
    
    <script src="jquery.min.js"></script>
    <script>
        $("ul li").click(function(){
            alert(123)
        });
    
        $("#add_li").click(function(){
            var $ele=$("<li>");
            $ele.text(Math.round(Math.random()*10));
            $("ul").append($ele)
    
        });
    
    
    //    $("ul").on("click","li",function(){
    //        alert(456)
    //    })
    
         $("#off").click(function(){
             $("ul li").off()
         })
        
    </script>
    <!DOCTYPE html>
    <!-- saved from url=(0041)http://v3.bootcss.com/examples/dashboard/ -->
    <html lang="zh-CN">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="http://v3.bootcss.com/favicon.ico">
    
        <title>Dashboard Template for Bootstrap</title>
    
        <!-- Bootstrap core CSS -->
        <link href="./Dashboard_files/bootstrap.min.css" rel="stylesheet">
    
        <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
        <link href="./Dashboard_files/ie10-viewport-bug-workaround.css" rel="stylesheet">
    
        <!-- Custom styles for this template -->
        <link href="./Dashboard_files/dashboard.css" rel="stylesheet">
    
        <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
        <!--[if lt IE 9]>
        <script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
        <script src="Dashboard_files/ie-emulation-modes-warning.js"></script>
    
        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!--[if lt IE 9]>
        <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    
    
        <style>
            .menu {
                margin: 0 -20px;
                border-bottom: 1px solid #336699;
            }
    
            .head {
                padding: 15px;
            }
    
            .my-table-tool {
                margin-bottom: 15px;
            }
    
            .menu .nav-sidebar > li > a {
                padding-right: 40px;
                padding-left: 40px;
            }
        </style>
    
    </head>
    
    <body>
    
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                        aria-expanded="false" aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="http://v3.bootcss.com/examples/dashboard/#">Project name</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="http://v3.bootcss.com/examples/dashboard/#">Dashboard</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/#">Settings</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/#">Profile</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/#">Help</a></li>
                </ul>
                <form class="navbar-form navbar-right">
                    <input type="text" class="form-control" placeholder="Search...">
                </form>
            </div>
        </div>
    </nav>
    
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-3 col-md-2 sidebar">
    
                <div class="menu">
                    <div class="head bg-primary">菜单一</div>
                    <ul class="nav nav-sidebar">
                        <li class=""><a href="http://v3.bootcss.com/examples/dashboard/#">Overview <span
                                class="sr-only">(current)</span></a>
                        </li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/#">Reports</a></li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/#">Analytics</a></li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/#">Export</a></li>
                    </ul>
                </div>
    
                <div class="menu">
                    <div class="head  bg-primary">菜单二</div>
                    <ul class="nav nav-sidebar">
                        <li><a href="http://v3.bootcss.com/examples/dashboard/">Nav item</a></li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/">Nav item again</a></li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/">One more nav</a></li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/">Another nav item</a></li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/">More navigation</a></li>
                    </ul>
                </div>
    
                <div class="menu">
                    <div class="head  bg-primary">菜单三</div>
                    <ul class="nav nav-sidebar">
                        <li><a href="http://v3.bootcss.com/examples/dashboard/">Nav item again</a></li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/">One more nav</a></li>
                        <li><a href="http://v3.bootcss.com/examples/dashboard/">Another nav item</a></li>
                    </ul>
                </div>
    
    
            </div>
            <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
    
                <div class="panel panel-primary">
                    <div class="panel-heading">Panel heading without title</div>
                    <div class="panel-body">
    
                        <!-- 表格上面的按钮-->
    
                        <div class="row my-table-tool">
                            <div class="col-md-12">
                                <button class="btn btn-success" data-toggle="modal" data-target="#myModal">添加</button>
                            </div>
                        </div>
    
                        <div class="table-responsive table-bordered">
                            <table id="t1" class="table table-striped table-bordered">
                                <thead>
                                <tr>
                                    <th>#</th>
                                    <th>用户名</th>
                                    <th>邮箱</th>
                                    <th>爱好</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td>1</td>
                                    <td>Egon</td>
                                    <td>egon@oldboyedu.com</td>
                                    <td>杠娘</td>
                                    <td>
                                        <button class="btn btn-warning">编辑</button>
                                        <button class="btn btn-danger">删除</button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>2</td>
                                    <td>Yuan</td>
                                    <td>yuanhao@oldboyedu.com</td>
                                    <td>日天</td>
                                    <td>
                                        <button class="btn btn-warning">编辑</button>
                                        <button class="btn btn-danger">删除</button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>3</td>
                                    <td>Alex</td>
                                    <td>alex@oldboyedu.com</td>
                                    <td>吹牛</td>
                                    <td>
                                        <button class="btn btn-warning">编辑</button>
                                        <button class="btn btn-danger">删除</button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>4</td>
                                    <td>GDP</td>
                                    <td>GDP@S6.com</td>
                                    <td>戴帽子</td>
                                    <td>
                                        <button class="btn btn-warning">编辑</button>
                                        <button class="btn btn-danger">删除</button>
                                    </td>
                                </tr>
    
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
    
    
            </div>
        </div>
    </div>
    
    
    <!--模态框开始 -->
    <div id="myModal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">xxxx</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="modal-username" class="col-sm-2 control-label">用户名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="modal-username" placeholder="用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="modal-email" class="col-sm-2 control-label">邮箱</label>
                            <div class="col-sm-10">
                                <input type="email" class="form-control" id="modal-email" placeholder="邮箱">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="modal-habit" class="col-sm-2 control-label">爱好</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="modal-habit" placeholder="爱好">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary">提交</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    <!--模态框结束 -->
    
    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="Dashboard_files/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"></script>')</script>
    <script src="Dashboard_files/bootstrap.min.js"></script>
    <!-- Just to make our placeholder images work. Don't actually copy the next line! -->
    <script src="Dashboard_files/holder.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="Dashboard_files/ie10-viewport-bug-workaround.js"></script>
    
    <script>
        $(document).ready(function () {
            $(".head").on("click", function () {
                // 兄弟标签 紧挨着的ul标签 隐藏  addClass("hide")
                $(this).parent().siblings().children("ul").slideUp();
                // 把自己 紧挨着的ul标签显示  removeClass("hide")
    //        $(this).next().removeClass("hide");
                $(this).next().slideToggle();
            })
    
            // 删除
            //    $("td>.btn-danger").click(function () {
            //        $(this).parent().parent().remove();
            //    })
    
            $("tbody").on("click", "td>.btn-danger", function () {
                $(this).parent().parent().remove();
            })
    
            // 编辑
            $("tbody").on("click", "td>.btn-warning", function () {
                // 弹出模态框
                $("#myModal").modal("show");
                // 给模态框赋值
                // 1.取值
                var tds = $(this).parent().parent().children();
                var username = tds.eq(1).text();
                var email = tds.eq(2).text();
                var habit = tds.eq(3).text();
                // 给模态框赋值
                $("#modal-username").val(username);
                $("#modal-email").val(email);
                $("#modal-habit").val(habit);
    
                // 把tds保存到myModal的data
                $("#myModal").data("tds", tds);
            });
            // 点击模态框上的提交按钮
            $(".modal-footer>.btn-primary").click(function () {
                // 1. 隐藏模态框
                $("#myModal").modal("hide");
                // 2. 更新td的值
                // 取值
                var username = $("#modal-username").val();
                var email = $("#modal-email").val();
                var habit = $("#modal-habit").val();
                // 赋值
                var tds = $("#myModal").data("tds");
                if (tds === undefined) {
                    // 这是添加
                    // 1.取值
                    // 2. 在表格添加新的一行tr
                    var trTmp = document.createElement("tr");
                    // 第一个td是序号
                    $(trTmp).append("<td>" + ($("tbody tr").size() + 1) + "</td>");
                    // 第二个td是username
                    $(trTmp).append("<td>" + username + "</td>");
                    $(trTmp).append("<td>" + email + "</td>");
                    $(trTmp).append("<td>" + habit + "</td>");
                    // 最后加按钮
                    $(trTmp).append($("tbody tr:first").find("td").last().clone(true));
                    $("tbody").append(trTmp);
                } else {
                    tds.eq(1).text(username);
                    tds.eq(2).text(email);
                    tds.eq(3).text(habit);
                    // 清空tds
                    $("#myModal").removeData("tds");
                }
    
            });
    
            // 添加按钮绑定的事件
            $(".my-table-tool .btn-success").click(function () {
                $("#myModal :input").val("");
            })
        })
    </script>
    </body>
    </html>
    经典

    十一 jQuery扩展

    1.jQuery.extend(object)

    扩展jQuery对象本身。

    用来在jQuery命名空间上增加新函数。 

    在jQuery命名空间上增加两个函数:

    <script>
        jQuery.extend({
          min: function(a, b) { return a < b ? a : b; },
          max: function(a, b) { return a > b ? a : b; }
    });
    
    
        jQuery.min(2,3); // => 2
        jQuery.max(4,5); // => 5
    </script>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登录校验</title>
        <link rel="stylesheet" href="bootstrap-3.3.7/css/bootstrap.min.css">
        <style>
            .c1 {
                margin-top: 100px;
            }
        </style>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-4 c1 col-md-offset-4">
                <form class="form-horizontal" id="login">
                    <div class="form-group">
                        <label for="username" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="username" placeholder="username" aria-describedby="helpBlock1" required="true">
                            <span id="helpBlock1" class="help-block"></span>
                        </div>
    
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <input type="password" class="form-control" id="inputPassword3" placeholder="Password" aria-describedby="helpBlock2">
                            <span id="helpBlock2" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox"> Remember me
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-default">Sign in</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="jquery-3.2.1.js"></script>
    <script src="bootstrap-3.3.7/js/bootstrap.min.js"></script>
    <script src="myValidate.js"></script
    <script>
        $(document).ready(function () {
             $.myValidate("#login")
          
        })
    </script>
    </body>
    </html>
    登录
    /**
     * Created by Administrator on 2017/10/17.
     */
    
    (function (jq) {
        jq.extend({
            "myValidate": function (form) {
                var formObj = jq(form);
    
                formObj.find(":submit").on("click", function () {
                    // 先清空状态
                    formObj.find(".form-group").removeClass("has-error");
                    formObj.find("span").text("");
    
                    // each循环
                    formObj.find("input").each(function () {
                        // 做判断
                        if (jq(this).val().length === 0) {
                            // 给他的爸爸加has-error
                            jq(this).parent().parent().addClass("has-error");
                            // 给span写内容
                            // 找到我这是什么input  --> 找到对应的label的文本内容
                            var name = jq(this).parent().prev().text();
                            jq(this).next().text(name + "不能为空");
                            return false;
                        }
                    });
                    return alse;
                });
            }
        })
    
    })(jQuery);
    myValidate.js

    2.jQuery.fn.extend(object)

    扩展 jQuery 元素集来提供新的方法(通常用来制作插件)

    增加两个插件方法:

    <body>
    
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    
    <script src="jquery.min.js"></script>
    <script>
        jQuery.fn.extend({
          check: function() {
             $(this).attr("checked",true);
          },
          uncheck: function() {
             $(this).attr("checked",false);
          }
        });
    
    
        $(":checkbox:gt(0)").check()
    </script>
    
    </body>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登录校验</title>
        <link rel="stylesheet" href="bootstrap-3.3.7/css/bootstrap.min.css">
        <style>
            .c1 {
                margin-top: 100px;
            }
        </style>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-4 c1 col-md-offset-4">
                <form class="form-horizontal" id="login">
                    <div class="form-group">
                        <label for="username" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="username" placeholder="username" aria-describedby="helpBlock1" required="true">
                            <span id="helpBlock1" class="help-block"></span>
                        </div>
    
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <input type="password" class="form-control" id="inputPassword3" placeholder="Password" aria-describedby="helpBlock2">
                            <span id="helpBlock2" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox"> Remember me
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-default">Sign in</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="jquery-3.2.1.js"></script>
    <script src="bootstrap-3.3.7/js/bootstrap.min.js"></script>
    <!--<script src="myValidate.js"></script>-->
    <script src="myValidate2.js"></script>
    <script>
        $(document).ready(function () {
    //        $.myValidate("#login")
            // 给jQuery对象扩展
            // $.fn.extend()
            $("#login").myValidate({"username": {"min-length": 6}});
        })
    </script>
    </body>
    </html>
    登录
    /**
     * Created by Administrator on 2017/10/17.
     */
    
    (function (jq) {
        jq.fn.extend({
            "myValidate": function (arg) {
                // this --> .前面的那个jQuery对象
                var formObj = this;
                formObj.find(":submit").on("click", function () {
                    // this --> 提交的submit按钮
                    // 先清空状态
                    formObj.find(".form-group").removeClass("has-error");
                    formObj.find("span").text("");
                    // each循环
                    var flag = true;
                    formObj.find("input[required='true']").each(function () {
                        // this --> input框
                        // 做判断
                        if (jq(this).val().length === 0) {
                            // 给他的爸爸加has-error
                            jq(this).parent().parent().addClass("has-error");
                            // 给span写内容
                            // 找到我这是什么input  --> 找到对应的label的文本内容
                            var name = jq(this).parent().prev().text();
                            jq(this).next().text(name + "不能为空");
                            flag = false;
                            return false;
                        }
    
                        var inputID = jq(this).attr("id");
                        var minLength = arg[inputID]["min-length"];
                        if (minLength !== undefined) {
                            if (jq(this).val().length < minLength) {
                                console.log("长度太短");
                                 // 给他的爸爸加has-error
                            jq(this).parent().parent().addClass("has-error");
                            // 给span写内容
                            // 找到我这是什么input  --> 找到对应的label的文本内容
                            var name = jq(this).parent().prev().text();
                            jq(this).next().text(name + "长度太短");
                                flag = false;
                                return false;
                            }
                        }
                    });
                    return flag;
                })
            }
        })
    })(jQuery);
    myValidate2.js
  • 相关阅读:
    使用Fiddler模拟客户端http响应
    Vim显示行号
    Convert int to byte array
    bare linefeeds received in ASCII mode
    Memory Analyse Tool
    what is the difference between static and normal variables in c++
    Looper Could not create wake pip
    Convert Java Doc to CHM using jd2chm
    ARM(RISC)和x86(CISC)的技术差异
    处理器架构——从RISC与CISC到x86、ARM、MIPS
  • 原文地址:https://www.cnblogs.com/ctztake/p/7678587.html
Copyright © 2011-2022 走看看