• jQuery攻略


    一、简介

    1.介绍
      jQuery是一个快速、简洁的JavaScript框架,是继Prototype之后又一个优秀的JavaScript代码库(或JavaScript框架)。jQuery设计的宗旨是“write Less,Do More”,
    即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。

    2.优势

    • 一款轻量级的JS框架。jQuery核心js文件才几十kb,不会影响页面加载速度。
    • 丰富的DOM选择器,jQuery的选择器用起来很方便,比如要找到某个DOM对象的相邻元素,JS可能要写好几行代码,而jQuery一行代码就搞定了,再比如要将一个表格的隔行变色,jQuery也是一行代码搞定。
    • 链式表达式。jQuery的链式操作可以把多个操作写在一行代码里,更加简洁。
    • 事件、样式、动画支持。jQuery还简化了js操作css的代码,并且代码的可读性也比js要强。
    • Ajax操作支持。jQuery简化了AJAX操作,后端只需返回一个JSON格式的字符串就能完成与前端的通信。
    • 跨浏览器兼容。jQuery基本兼容了现在主流的浏览器,不用再为浏览器的兼容问题而伤透脑筋。
    • 插件扩展开发。jQuery有着丰富的第三方的插件,例如:树形菜单、日期控件、图片切换插件、弹出窗口等等基本前端页面上的组件都有对应插件,并且用jQuery插件做出来的效果很炫,并且可以根据自己需要去改写和封装插件,简单实用。

    3.jQuery内容

    • 选择器
    • 筛选器
    • 样式操作
    • 文本操作
    • 属性操作
    • 文档处理
    • 事件
    • 动画效果
    • 插件
    • each、data、Ajax

    4.jQuery对象
      jQuery对象就是通过jQuery包装DOM对象后产生的对象。jQuery对象是 jQuery独有的。如果一个对象是 jQuery对象,那么它就可以使用jQuery里的方法:例如$(“#i1”).html()。

      $("#i1").html()的意思是:获取id值为 i1的元素的html代码。其中 html()是jQuery里的方法。

      相当于: document.getElementById("i1").innerHTML;

      虽然 jQuery对象是包装 DOM对象后产生的,但是 jQuery对象无法使用 DOM对象的任何方法,同理 DOM对象也没不能使用 jQuery里的方法。

      一个约定,我们在声明一个jQuery对象变量的时候在变量名前面加上$:

    var $variable = jQuery对像
    var variable = DOM对象
    $variable[0]//jQuery对象转成DOM对象

      拿上面那个例子举例,jQuery对象和DOM对象的使用:

    $("#i1").html();//jQuery对象可以使用jQuery的方法
    $("#i1")[0].innerHTML;// DOM对象使用DOM的方法
    

      

    二、查找元素
    1.选择器
    (1)基本选择器

    id选择器:
    $("#id")
    
    标签选择器:
    $("tagName")
    
    class选择器:
    $(".className")
    
    配合使用:
    $("div.c1")  // 找到有c1 class类的div标签
    
    所有元素选择器:
    $("*")
    
    组合选择器:
    $("#id, .className, tagName")
    

      

    (2)层级选择器

    $("x y"); // x的所有后代y(子子孙孙)
    $("x > y"); // x的所有儿子y(儿子)
    $("x + y"); // 找到所有紧挨在x后面的y
    $("x ~ y"); // x之后所有的兄弟y
    

    (3)内容选择器

    :first // 第一个
    :last // 最后一个
    :eq(index)// 索引等于index的那个元素
    :even // 匹配所有索引值为偶数的元素,从 0 开始计数
    :odd // 匹配所有索引值为奇数的元素,从 0 开始计数
    :gt(index)// 匹配所有大于给定索引值的元素
    :lt(index)// 匹配所有小于给定索引值的元素
    :not(元素选择器)// 移除所有满足not条件的标签
    :has(元素选择器)// 选取所有包含一个或多个标签在其内的标签(指的是从后代元素找)
    

      

    (4)表单选择器

    $(":input") //匹配所有 input, textarea, select 和 button 元素
    $(":text") //所有的单行文本框
    $(":password") //所有密码框
    $(":radio") //所有单选按钮
    $(":checkbox") //所有复选框
    $(":submit") //所有提交按钮
    $(":reset") //所有重置按钮
    $(":button") //所有button按钮
    $(":file") //所有文件域
    
    $("input:checked")    //所有选中的元素
    $("select option:selected")    //select中所有选中的option元素
    表单对象属性:
    :enabled
    :disabled
    :checked
    :selected
    

      

    exp:找到可用的input标签
    <form>
      <input name="email" disabled="disabled" />
      <input name="id" />
    </form>
    $("input:enabled")  // 找到可用的input标签
    
    
    exp:找到被选中的option:
    <select id="s1">
      <option value="beijing">北京市</option>
      <option value="shanghai">上海市</option>
      <option selected value="guangzhou">广州市</option>
      <option value="shenzhen">深圳市</option>
    </select>
    
    $(":selected")  // 找到所有被选中的option
    示例

    (5)属性选择器

    [attribute]
    [attribute=value]// 属性等于
    [attribute!=value]// 属性不等于
    

      

    exp:
    <input type="text">
    <input type="password">
    <input type="checkbox">
    $("input[type='checkbox']");// 取到checkbox类型的input标签
    $("input[type!='text']");// 取到类型不是text的input标签
    示例

    2.筛选器

    (1)基本筛选器

    $("#id").eq(0) //当前操作中第N个jQuery对象,类似索引
    $("#id").first() //第一个元素
    $("#id").last() //最后一个元素
    $(this).hasClass("test") //元素是否含有某个特定的类,返回布尔值
    $("#id").has('ul') //包含特定后代的元素
    

      

    (2)下一个元素

    $("#id").next()
    $("#id").nextAll()
    $("#id").nextUntil("#i2")
    

      

    (3)上一个元素

    $("#id").prev()
    $("#id").prevAll()
    $("#id").prevUntil("#i2")
    

      

    (4)父亲元素

    $("#id").parent()
    $("#id").parents() // 查找当前元素的所有的父辈元素
    $("#id").parentsUntil() // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。
    

      

    (5)儿子和兄弟元素

    $("#id").children();// 儿子们
    $("#id").siblings();// 兄弟们
    

      

    (6)查找 搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。

    $("div").find("p")
    
    等价于$("div p")
    

      

    (7)筛选 筛选出与指定表达式匹配的元素集合。这个方法用于缩小匹配的范围。用逗号分隔多个表达式。

    $("div").filter(".c1") // 从结果集中过滤出有c1样式类的
    
    等价于 $("div.c1")
    

      

    三、操作标签
    1.属性操作
    (1)用于ID等或自定义属性:

    attr(attrName)// 返回第一个匹配元素的属性值
    attr(attrName, attrValue)// 为所有匹配元素设置一个属性值
    attr({k1: v1, k2:v2})// 为所有匹配元素设置多个属性值
    removeAttr()// 从每一个匹配的元素中删除一个属性


    (2)用于checkbox和radio

    prop() // 获取属性
    removeProp() // 移除属性
    

      

    <input type="checkbox" value="1">
    <input type="radio" value="2">
    <script>
      $(":checkbox[value='1']").prop("checked", true);
      $(":radio[value='2']").prop("checked", true);
    </script>
    prop
    prop和attr的区别:
    
    attr全称attribute(属性)
    
    prop全称property(属性)
    
    虽然都是属性,但他们所指的属性并不相同,attr所指的属性是HTML标签属性,而prop所指的是DOM对象属性,可以认为attr是显式的,而prop是隐式的。
    
    举个例子:
    
    <input type="checkbox" id="i1" value="1">
    针对上面的代码,
    
    $("#i1").attr("checked")  // undefined
    $("#i1").prop("checked")  // false
    可以看到attr获取一个标签内没有的东西会得到undefined,而prop获取的是这个DOM对象的属性,因此checked为false。
    
    如果换成下面的代码:
    
    <input type="checkbox" checked id="i1" value="1">
    再执行:
    
    $("#i1").attr("checked")   // checked
    $("#i1").prop("checked")  // true
    这已经可以证明attr的局限性,它的作用范围只限于HTML标签内的属性,而prop获取的是这个DOM对象的属性,选中返回true,没选中返回false。
    
    接下来再看一下针对自定义属性,attr和prop又有什么区别:
    
    <input type="checkbox" checked id="i1" value="1" me="自定义属性">
    执行以下代码:
    
    $("#i1").attr("me")   // "自定义属性"
    $("#i1").prop("me")  // undefined
    可以看到prop不支持获取标签的自定义属性。
    
    总结一下:
    
    对于标签上有的能看到的属性和自定义属性都用attr
    对于返回布尔值的比如checkbox、radio和option的是否被选中都用prop。
    attr和prop区别

    2.CSS类操作

    addClass();// 添加指定的CSS类名。
    removeClass();// 移除指定的CSS类名。
    toggleClass();// 切换CSS类名,如果有就移除,如果没有就添加。
    hasClass();// 判断样式存不存在
    

      

    <script>
        $("p").click(function () {
            // $(this).css("color","red");
            // $(this).css("font-size","30px");
            $(this).css({"color":"red","font-size":"30px"})
        })
    </script>
    

     

    3.HTML代码和文本值

    HTML代码:
    html()// 取得第一个匹配元素的html内容
    html(val)// 设置所有匹配元素的html内容
    
    文本值:
    text()// 取得所有匹配元素的内容
    text(val)// 设置所有匹配元素的内容
    
    值:
    val()// 取得第一个匹配元素的当前值
    val(val)// 设置所有匹配元素的值
    val([val1, val2])// 设置多选的checkbox、多选select的值
    

      

    $('p').html();               //返回p元素的html内容
    $("p").html("Hello <b>nick</b>!");  //设置p元素的html内容
    $('p').text();               //返回p元素的文本内容
    $("p").text("nick");           //设置p元素的文本内容
    $("input").val();             //获取文本框中的值
    $("input").val("nick");          //设置文本框中的内容
    

      

    <input type="checkbox" value="basketball" name="hobby">篮球
    <input type="checkbox" value="football" name="hobby">足球
    
    <select multiple id="s1">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    
    设置值:
    
    $("[name='hobby']").val(['basketball', 'football']);
    $("#s1").val(["1", "2"])
    

      

    4.位置操作

    • offset()// 获取匹配元素在当前窗口的相对偏移或设置元素位置
    • position()// 获取匹配元素相对父元素的偏移
    • scrollTop()// 获取匹配元素相对滚动条顶部的偏移
    • scrollLeft()// 获取匹配元素相对滚动条左侧的偏移
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="x-ua-compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>位置相关示例之返回顶部</title>
    
      <!--<link href="https://cdn.bootcss.com/normalize/8.0.1/normalize.css" rel="stylesheet">-->
      <style>
        .c1 {
           100px;
          height: 200px;
          background-color: red;
        }
    
        .c2 {
          height: 50px;
           50px;
    
          position: fixed;
          bottom: 15px;
          right: 15px;
          background-color: #2b669a;
        }
        .hide {
          display: none;
        }
        .c3 {
          height: 100px;
        }
      </style>
    
    </head>
    <body>
    <button id="b1" class="btn btn-default">点我</button>
    <div class="c1"></div>
    <div class="c3">1</div>
    <div class="c3">2</div>
    <div class="c3">3</div>
    <div class="c3">4</div>
    <div class="c3">5</div>
    <div class="c3">6</div>
    <div class="c3">7</div>
    <div class="c3">8</div>
    <div class="c3">9</div>
    <div class="c3">10</div>
    <div class="c3">11</div>
    <div class="c3">12</div>
    <div class="c3">13</div>
    <div class="c3">14</div>
    <div class="c3">15</div>
    <div class="c3">16</div>
    <div class="c3">17</div>
    <div class="c3">18</div>
    
    <button id="b2" class="btn btn-default c2 hide">返回顶部</button>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
      $("#b1").click(function () {
        $(".c1").offset({left: 200, top:200});
      });
    
      $(window).scroll(function () {
        if ($(window).scrollTop() > 100) {
          $("#b2").removeClass("hide");
        }else {
          $("#b2").addClass("hide");
        }
      });
      $("#b2").click(function () {
        $(window).scrollTop(0);
      })
    </script>
    </body>
    </html>
    返回顶部

    5.尺寸

    height()    //获取元素的高度
    width()     //获取元素的宽度
    innerHeight()   //获取元素内部区域高度(包括补白、不包括边框)
    innerWidth()    //获取元素内部区域宽度(包括补白、不包括边框)
    outerHeight()    //匹配元素外部高度(默认包括补白和边框)
    outerWidth()    //匹配元素外部宽度(默认包括补白和边框)
    outerHeight(true)    //为true时包括边距
    

      

    四、文档操作

    添加到指定元素内部的后面
    $(A).append(B)// 把B追加到A
    $(A).appendTo(B)// 把A追加到B
    
    添加到指定元素内部的前面
    $(A).prepend(B)// 把B前置到A
    $(A).prependTo(B)// 把A前置到B
    
    添加到指定元素外部的后面
    $(A).after(B)// 把B放到A的后面
    $(A).insertAfter(B)// 把A放到B的后面
    
    添加到指定元素外部的前面
    $(A).before(B)// 把B放到A的前面
    $(A).insertBefore(B)// 把A放到B的前面
    
    移除和清空元素
    remove()// 从DOM中删除所有匹配的元素。
    empty()// 删除匹配的元素集合中所有的子节点。
    
    克隆
    clone()// 参数
    

      

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>增加元素</title>
    </head>
    <body>
    
    
    <ul id="ul">
        <li id="li1">1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    
    <script src="jquery-3.3.1.min.js"></script>
    <script>
        // var liEle1 = document.createElement('li');
        // liEle1.innerText = "在最后增加的li标签";
        //在ul内部最后增加标签
        // $("#ul").append(liEle1);
    
        // $(liEle1).appendTo($("#ul"));
        //
        // var liEle2 = document.createElement('li');
        // liEle2.innerText = "在最前面增加的li标签";
        //在ul内部最前面增加标签
        // $("#ul").prepend(liEle2);
        // $(liEle2).prependTo($("#ul"))
    
        // var liEle3 = document.createElement('li');
        // liEle3.innerText = "在id为li1标签后面增加li标签";
        //同级增加
        // // $("#li1").after(liEle3)
        // $(liEle3).insertAfter($("#li1"));
    
    
        var liEle4 = document.createElement('li');
        liEle4.innerText = "在id为li1标签前面增加li标签";
        //同级增加
        // $("#li1").before(liEle4);
        $(liEle4).insertBefore($('#li1'));
    
        // $("#ul").remove(); //删除ul标签
        // $("#ul").empty();   //情况ul标签下的标签
    </script>
    </body>
    </html>
    文档操作
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>02点击在表格最后增加一条记录</title>
    </head>
    <body>
    <table border="1px">
        <thead>
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="t1">
        <tr>
            <td>1</td>
            <td>alina</td>
            <td>18</td>
            <td><button class="del">删除</button></td>
        </tr>
        <tr>
            <td>2</td>
            <td>felix</td>
            <td>20</td>
            <td><button class="del">删除</button></td>
        </tr>
        </tbody>
    </table>
    <button id="b1">增加一行数据</button>
    <script src="jquery-3.3.1.min.js"></script>
    
    <script>
        // 增加一行数据
        $("#b1").click(function () {
            var trEle = document.createElement("tr");
            $(trEle).html("<td>3</td><td>lisa</td><td>6</td><td><button class='del'>删除</button></td>");
            $("#t1").append($(trEle))
        });
    
        // 删除一行数据
        $(`.del`).click(function () {
            console.log('ok');
            $(this).parent().parent().remove();
        });
    
    </script>
    </body>
    </html>
    新增一条记录

    五、事件

    1.事件

    $("p").click();   //单击事件
    $("p").dblclick(); //双击事件
    $("input[type=text]").focus() //元素获得焦点时,触发 focus 事件
    $("input[type=text]").blur() //元素失去焦点时,触发 blur事件
    $("button").mousedown()//当按下鼠标时触发事件
    $("button").mouseup() //元素上放松鼠标按钮时触发事件
    $("p").mousemove() //当鼠标指针在指定的元素中移动时触发事件
    $("p").mouseover() //当鼠标指针位于元素上方时触发事件
    $("p").mouseout()  //当鼠标指针从元素上移开时触发事件
    $(window).keydown() //当键盘或按钮被按下时触发事件
    $(window).keypress() //当键盘或按钮被按下时触发事件,每输入一个字符都触发一次
    $("input").keyup() //当按钮被松开时触发事件
    $(window).scroll() //当用户滚动时触发事件
    $(window).resize() //当调整浏览器窗口的大小时触发事件
    $("input[type='text']").change() //当元素的值发生改变时触发事件
    $("input").select() //当input 元素中的文本被选择时触发事件
    $("form").submit() //当提交表单时触发事件
    $(window).unload() //用户离开页面时
    

      

    2.页面载入
      当DOM载入就绪可以查询及操纵时绑定一个要执行的函数,这是事件模块中最重要的一个函数,因为它可以极大地提高web应用程序的响应速度。
    可以在同一个页面中无限次地使用$(document).ready()事件。其中注册的函数会按照(代码中的)先后顺序依次执行。

    ready(fn)
    
    $(document).ready(function(){
    // 在这里写你的代码...
    });
    
    //简写
    $(function($) {
    do something...
    });
    

      

    Display a paragraph's text in an alert when it is clicked:
    
    $("p").on("click", function(){
    alert( $(this).text() );
    });
    Pass data to the event handler, which is specified here by name:
    
    function myHandler(event) {
    alert(event.data.foo);
    }
    $("p").on("click", {foo: "bar"}, myHandler)
    Cancel a form submit action and prevent the event from bubbling up by returning false:
    
    $("form").on("submit", false)
    Cancel only the default action by using .preventDefault().
    
    $("form").on("submit", function(event) {
      event.preventDefault();
    });
    Stop submit events from bubbling without preventing form submit, using .stopPropagation().
    
    $("form").on("submit", function(event) {
      event.stopPropagation();
    });
    示例

    3.事件绑定
    (1)在选择元素上绑定一个或多个事件的事件处理函数--- .on()

    .on(events,[selector],[data],fn)
    
    说明:
    events:一个或多个用空格分隔的事件类型和可选的命名空间,如"click"或"keydown.myPlugin" 。
    selector:一个选择器字符串用于过滤器的触发事件的选择器元素的后代。如果选择的< null或省略,当它到达选定的元素,事件总是触发。
    data:当一个事件被触发时要传递event.data给事件处理函数。
    fn:该事件被触发时执行的函数。 false 值也可以做一个函数的简写,返回false。
    

      

    (2)为每一个匹配元素的特定事件(像click)绑定一个一次性的事件处理函数--- .one()

    one(type,[data],fn)
    type:添加到元素的一个或多个事件。由空格分隔多个事件。必须是有效的事件。
    data:将要传递给事件处理函数的数据映射
    fn:每当事件触发时执行的函数。
    

      

    4.事件移除--- .off()
    在选择元素上移除一个或多个事件的事件处理函数。

    .off(events,[selector],[fn])
    events:一个或多个空格分隔的事件类型和可选的命名空间,或仅仅是命名空间,比如"click", "keydown.myPlugin", 或者 ".myPlugin".
    selector:一个最初传递到.on()事件处理程序附加的选择器。
    fn:事件处理程序函数以前附加事件上,或特殊值false.
    
    Remove all event handlers from all paragraphs:
    
    $("p").off()
    Remove all delegated click handlers from all paragraphs:
    
    $("p").off( "click", "**" )
    Remove just one previously bound handler by passing it as the third argument:
    
    var foo = function () {
    // code to handle some kind of event
    };
    
    // ... now foo will be called when paragraphs are clicked ...
    $("body").on("click", "p", foo);
    
    
    // ... foo will no longer be called.
    $("body").off("click", "p", foo);
    Unbind all delegated event handlers by their namespace:
    
    var validate = function () {
    // code to validate form entries
    };
    
    // delegate events under the ".validator" namespace
    $("form").on("click.validator", "button", validate);
    
    $("form").on("keypress.validator", "input[type='text']", validate);
    
    // remove event handlers in the ".validator" namespace
    
    $("form").off(".validator");
    示例

    5.阻止后续事件执行

    • return false; // 常见阻止表单提交等
    • e.preventDefault();
    $("p").click(function(event){  
     alert(event.type); //"click"  
    }); 
    
    (evnet object)属性方法:
    event.pageX   //事件发生时,鼠标距离网页左上角的水平距离
    event.pageY   //事件发生时,鼠标距离网页左上角的垂直距离
    event.type   //事件的类型
    event.which   //按下了哪一个键
    event.data   //在事件对象上绑定数据,然后传入事件处理函数
    event.target  //事件针对的网页元素
    event.preventDefault()  //阻止事件的默认行为(比如点击链接,会自动打开新页面)
    event.stopPropagation()  //停止事件向上层元素冒泡
    其他Event对象

    6.事件委托
      事件委托是通过事件冒泡的原理,利用父标签去捕获子标签的事件。

    $("table").on("click", ".delete", function () {
    // 删除按钮绑定的事件
    })
    

      

     六、效果

    基本

    $("p").show()        //显示隐藏的匹配元素
    $("p").show("slow");    //参数表示速度,("slow","normal","fast"),也可为900毫秒
    $("p").hide()        //隐藏显示的元素
    $("p").toggle();      //切换 显示/隐藏

    滑动

    $("p").slideDown("900");    //用900毫秒时间将段落滑下
    $("p").slideUp("900");     //用900毫秒时间将段落滑上
    $("p").slideToggle("900");  //用900毫秒时间将段落滑上,滑下

    淡入淡出

    $("p").fadeIn("900");        //用900毫秒时间将段落淡入
    $("p").fadeOut("900");       //用900毫秒时间将段落淡出
    $("p").fadeToggle("900");     //用900毫秒时间将段落淡入,淡出
    $("p").fadeTo("slow", 0.6);    //用900毫秒时间将段落的透明度调整到0.6

    七、其它

    1.遍历

    jQuery.each(collection, callback(indexInArray, valueOfElement)):

    描述:一个通用的迭代函数,它可以用来无缝迭代对象和数组。数组和类似数组的对象通过一个长度属性(如一个函数的参数对象)来迭代数字索引,从0到length - 1。其他对象通过其属性名进行迭代。

    .each(function(index, Element))  遍历一个jQuery对象,为每个匹配元素执行一个函数。

    .each() 方法用来迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,会传递当前循环次数作为参数(从0开始计数)。由于回调函数是在当前DOM元素为上下文的语境中触发的,所以关键字 this 总是指向这个元素。

    // 为每一个li标签添加foo
    $("li").each(function(){
      $(this).addClass("c1");
    });

    注意: jQuery的方法返回一个jQuery对象,遍历jQuery集合中的元素 - 被称为隐式迭代的过程。当这种情况发生时,它通常不需要显式地循环的 .each()方法:

    也就是说,上面的例子没有必要使用each()方法,直接像下面这样写就可以了:

    $("li").addClass("c1");  // 对所有标签做统一操作

    注意:

    在遍历过程中可以使用 return false提前结束each循环。

    终止each循环

    return false
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>10each循环</title>
    </head>
    <body>
    <div>111</div>
    <div>222</div>
    <div>333</div>
    <div>444</div>
    <div>555</div>
    <div>666</div>
    
    <script src="jquery-3.3.1.min.js"></script>
    <script>
        var $divEles = $("div");
        // for (var i=0;i<$divEles.length;i++) {
        //     console.log($divEles[i].innerText)
        // }
    
        // 循环所有div标签
        $divEles.each(function () {
            console.log(this.innerText)
        });
    
        // // 循环数组
        // var lst = [11,22,33,44,55]
        // $.each(lst,function (index,value) {
        //     console.log(index + ":" + value)
        // })
    
        // 循环数组
        var lst = [11,22,33,44,55]
        $.each(lst,function (index,value) {
            if (value===33) {
                // return false 类似于break 退出当前循环
    
                //退出当前这一次循环 类似于continue
                return;
            }
            console.log(index + ":" + value);
        })
    
    </script>
    
    </body>
    </html>
    each示例

    2.数据缓存

      在匹配的元素集合中的所有元素上存储任意相关数据或返回匹配的元素集合中的第一个元素的给定名称的数据存储的值。

    .data(key, value):  在匹配的元素上存储任意相关数据。

    $("div").data("blah");  // undefined
    $("div").data("blah", "hello");  // blah设置为hello
    $("div").data("blah");  // hello
    $("div").data("blah", 86);  // 设置为86
    $("div").data("blah");  //  86
    $("div").removeData("blah");  //移除blah
    $("div").data("blah");  // undefined
    

      

    .removeData(key):  移除存放在元素上的数据,不加key参数表示移除所有保存的数据。

    $("div").removeData("k");  //移除元素上存放k对应的数据
    

      

    3.插件

    jQuery.extend(object)  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>
    

      

    jQuery.fn.extend(object)  一个对象的内容合并到jQuery的原型,以提供新的jQuery实例方法。

    <script>
      jQuery.fn.extend({
        check:function(){
          return this.each(function(){this.checked =true;});
        },
        uncheck:function(){
          return this.each(function(){this.checked =false;});
        }
      });
    // jQuery对象可以使用新添加的check()方法了。
    $("input[type='checkbox']").check();
    </script>
    

      

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>插件</title>
    </head>
    <body>
    <div class="c1">插件</div>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
        $.fn.extend({
                "myprint": function () {
                    console.log("加油!努力学好JS!")
                }
            }
        );
    
        $.extend({
                "myconsole": function () {
                    console.log("加油!努力学好JS!")
                }
            }
        )
    </script>
    
    $(".c1").myprint();
    //加油!努力学好JS!
    $.myconsole();
    </body>
    </html>
    示例

     

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>登录校验完整版</title>
        <style>
            .error {
                color: red;
            }
        </style>
    </head>
    <body>
    <form id="f1">
        <p>
            <label>用户名:
                <input class="need" name="username" type="text">
                <span class="error"></span>
            </label>
        </p>
        <p>
            <label>密码:
                <input class="need" name="password" type="password">
                <span class="error"></span>
            </label>
        </p>
    
        <p>爱好:
            <label>篮球
                <input name="hobby" value="basketball" type="checkbox">
            </label>
            <label>足球
                <input name="hobby" value="football" type="checkbox">
            </label>
            <label>双色球
                <input name="hobby" value="doublecolorball" type="checkbox">
            </label>
        </p>
    
        <p>性别:
            <label><input name="gender" value="1" type="radio">
            </label>
            <label><input name="gender" value="0" type="radio">
            </label>
            <label>保密
                <input name="gender" value="2" type="radio">
            </label>
        </p>
    
        <p>
            <label for="s1">从哪儿来:</label>
            <select name="from" id="s1">
                <option value="010">北京</option>
                <option value="021">上海</option>
                <option value="020">广州</option>
            </select>
        </p>
        <p>
            <label for="s2">从哪儿来:</label>
            <select name="from" id="s2" multiple>
                <option value="010">北京</option>
                <option value="021">上海</option>
                <option value="020">广州</option>
                <option value="0755">深圳</option>
            </select>
        </p>
        <p>
            <label for="t1">个人简介:</label>
            <textarea name="memo" id="t1" cols="30" rows="10">
    
            </textarea>
        </p>
        <p>
            <input id="b1" type="submit" value="登录">
            <input id="cancel" type="button" value="取消">
        </p>
    </form>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
        // 点击登录按钮验证用户名和密码为不为空
        // 为空就在对应的input标签下面显示一个错误提示信息
    
        // 1. 给登录按钮绑定点击事件
        // 2. 点击事件要做的事儿
        // 2.1 找到input标签--> 取值 --> 判断为不为空 --> .length为不为0
        // 2.2 如果不为空,则什么都不做
        // 2.2 如果为空,要做几件事儿
        // 2.2.1 在当前这个input标签的下面 添加一个新的标签,内容为xx不能为空
    
        $("#b1").click(function () {
            var $needEles = $(".need");
            // 定义一个标志位
            var flag = true;
            for (var i = 0; i < $needEles.length; i++) {
                // 如果有错误
                if ($($needEles[i]).val().trim().length === 0) {
                    var labelName = $($needEles[i]).parent().text().trim().slice(0, -1);
                    console.log($($needEles[i]).next().text().length);
                    if ($($needEles[i]).next().text().length === 0) {
                        $($needEles[i]).next().text(labelName + "不能为空!");
                    }
    
                    // 将标志位置为false
                    flag = false;
                    break;
                }
            }
            return flag;
        })
    
    </script>
    </body>
    </html>
    登录校验
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>键盘相关事件</title>
    
    </head>
    <body>
    
    <table border="1" id="t1">
        <thead>
        <tr>
            <th>#</th>
            <th>姓名</th>
            <th>爱好</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td><input type="checkbox"></td>
            <td>小强</td>
            <td>吃冰激凌</td>
            <td>
                <select>
                    <option value="0">下线</option>
                    <option value="1">上线</option>
                    <option value="2">离线</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>二哥</td>
            <td>Girl</td>
            <td>
                <select>
                    <option value="0">下线</option>
                    <option value="1">上线</option>
                    <option value="2">离线</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>二哥</td>
            <td>Girl</td>
            <td>
                <select>
                    <option value="0">下线</option>
                    <option value="1">上线</option>
                    <option value="2">离线</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>二哥</td>
            <td>Girl</td>
            <td>
                <select>
                    <option value="0">下线</option>
                    <option value="1">上线</option>
                    <option value="2">离线</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>二哥</td>
            <td>Girl</td>
            <td>
                <select>
                    <option value="0">下线</option>
                    <option value="1">上线</option>
                    <option value="2">离线</option>
                </select>
            </td>
        </tr>
    
        </tbody>
    </table>
    <p>提示:按下Ctrl键可批量操作状态</p>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
        // 确保绑定事件的时候DOM树是生成好的
        $(document).ready(function () {
            var mode = false;
            var $bodyEle = $("body");
            // 给文档绑定 监听键盘按键被按下去的事件
            $bodyEle.on("keydown", function (event) {
                //
                console.log(event.keyCode);
                if (event.keyCode === 17) {
                    // 进入批量操作模式
                    mode = true;
                }
            });
            // 按键抬起来的时候,退出批量操作模式
            $bodyEle.on("keyup", function (event) {
                //
                console.log(event.keyCode);
                if (event.keyCode === 17) {
                    // 进入批量操作模式
                    mode = false;
                }
            });
    
            $("select").on("change", function () {
                // 取到当前select的值
                var value = $(this).val();
                // console.log(value);
                var $thisCheckbox = $(this).parent().siblings().first().find(":checkbox");
                // 判断checkbox有没有被选中
                if ($thisCheckbox.prop("checked") && mode) {
                    // 真正进入批量操作模式
                    var $checkedEles = $("input[type='checkbox']:checked");
                    for (var i = 0; i < $checkedEles.length; i++) {
                        // 找到同一行的select
                        $($checkedEles[i]).parent().siblings().last().find("select").val(value);
                    }
                }
            })
        });
    </script>
    </body>
    </html>
    键盘事件
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>08动画效果</title>
    </head>
    <body>
    <img src="https://www.python.org/static/img/python-logo.png" alt="">
    <img src="test.png" alt="">
    <script src="jquery-3.3.1.min.js"></script>
    
    <script>
        $("img").hide(5000);
        $("img").toggle(5000);
    </script>
    </body>
    </html>
    动画效果
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
          <button id="in">fadein</button>
          <button id="out">fadeout</button>
          <button id="toggle">fadetoggle</button>
          <button id="fadeto">fadeto</button>
    
          <div id="id1" style="display:none;  80px;height: 80px;background-color: blueviolet"></div>
          <div id="id2" style="display:none;  80px;height: 80px;background-color: orangered "></div>
          <div id="id3" style="display:none;  80px;height: 80px;background-color: darkgreen "></div>
    
        <script src="jquery-3.3.1.min.js"></script>
        <script>
            $(document).ready(function(){
                $("#in").click(function(){
                   $("#id1").fadeIn(3000);
                   $("#id2").fadeIn(3000);
                   $("#id3").fadeIn(3000);
    
                });
                $("#out").click(function(){
                   $("#id1").fadeOut(3000);
                   $("#id2").fadeOut(3000);
                   $("#id3").fadeOut(3000);
    
                });
                $("#toggle").click(function(){
                   $("#id1").fadeToggle(3000);
                   $("#id2").fadeToggle(3000);
                   $("#id3").fadeToggle(3000);
    
                });
                $("#fadeto").click(function(){
                   $("#id1").fadeTo(3000,0.4);
                   $("#id2").fadeTo(3000,0.5);
                   $("#id3").fadeTo(3000,0);
                });
            });
        </script>
    </body>
    </html>
    淡入淡出
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            #flipshow,#content,#fliphide,#toggle{
                padding: 5px;
                text-align: center;
                background-color: blueviolet;
                border:solid 1px red;
    
            }
            #content{
                padding: 50px;
                display: none;
            }
        </style>
    </head>
    <body>
    
        <div id="flipshow">出现</div>
        <div id="fliphide">隐藏</div>
        <div id="toggle">toggle</div>
        <div id="content">helloworld</div>
    
        <script src="jquery-3.3.1.min.js"></script>
        <script>
            $(document).ready(function(){
                  $("#flipshow").click(function(){
                     $("#content").slideDown(1000);
                  });
                  $("#fliphide").click(function(){
                     $("#content").slideUp(1000);
                  });
                  $("#toggle").click(function(){
                     $("#content").slideToggle(1000);
                  })
              });
        </script>
    
    </body>
    </html>
    滑动
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width">
        <meta http-equiv="X-UA-Compatible" content="IE=8">
        <title>购物商城</title>
    
        <style>
                *{
                    margin: 0;
                    padding: 0;
                }
                .outer{
                    position:relative;
                    width:350px;
                    height:350px;
                    border:1px solid black;
                }
                .outer .small-box{
                    position: relative;
                    z-index: 1;
                }
                .outer .small-box .mark{
                    position: absolute;
                    display: block;
                    width: 350px;
                    height: 350px;
                    background-color: #fff;
                    filter: alpha(opacity=0);
                    opacity: 0;
                    z-index: 10;
                }
                .outer .small-box .float-box{
                    display: none;
                    width: 175px;
                    height: 175px;
                    position: absolute;
                    background: #DAEEFC;
                    filter: alpha(opacity=40);
                    opacity: 0.4;
                }
                .outer .big-box{
                    position: absolute;
                    top: 0;
                    left: 351px;
                    width: 350px;
                    height: 350px;
                    overflow: hidden;
                    border: 1px solid transparent;
                    z-index: 1;
                }
                .outer .big-box img{
                    position: absolute;
                    z-index: 5
                }
        </style>
    </head>
    <body>
    
        <div  class="outer">
            <div  class="small-box">
                <div  class="mark"></div>
                <div  class="float-box" ></div>
                <img width="350" height="350" src="1.jpg">
            </div>
            <div class="big-box">
                <img width="900px" height="900px" src="1.jpg" >
            </div>
        </div>
    
    
    <script src="jquery-3.3.1.min.js"></script>
    
    <script>
       $(function(){
            $(".mark").mouseover(function () {
                $(".float-box").css("display","block");
                $(".big-box").css("display","block");
            });
    
            $(".mark").mouseout(function () {
                $(".float-box").css("display","none");
                $(".big-box").css("display","none");
            });
    
    
    
            $(".mark").mousemove(function (e) {
    
                var _event = e || window.event;  //兼容多个浏览器的event参数模式
    
                var float_box_width  = $(".float-box")[0].offsetWidth;
                var float_box_height = $(".float-box")[0].offsetHeight;//175,175
    
    
                var float_box_width_half  =  float_box_width / 2;
                var float_box_height_half =  float_box_height/ 2;//87.5,87.5
    
    
                var small_box_width  =  $(".outer")[0].offsetWidth;
                var small_box_height =  $(".outer")[0].offsetHeight;//360,360
    
    
                var mouse_left = _event.clientX   - float_box_width_half;
                var mouse_top = _event.clientY  - float_box_height_half;
    
    
                if (mouse_left < 0) {
                    mouse_left = 0;
                } else if (mouse_left > small_box_width - float_box_width) {
                    mouse_left = small_box_width - float_box_width;
                }
                if (mouse_top < 0) {
                    mouse_top = 0;
                } else if (mouse_top > small_box_height - float_box_height) {
                    mouse_top = small_box_height - float_box_height;
                }
    
                $(".float-box").css("left",mouse_left + "px");
                $(".float-box").css("top",mouse_top + "px");
    
    
                var percentX = ($(".big-box img")[0].offsetWidth - $(".big-box")[0].offsetWidth) / (small_box_width - float_box_width);
                var percentY = ($(".big-box img")[0].offsetHeight - $(".big-box")[0].offsetHeight) / (small_box_height - float_box_height);
                console.log($(".big-box img")[0].offsetWidth,$(".big-box")[0].offsetWidth,small_box_width,float_box_width)
                console.log(percentX,percentY)
                $(".big-box img").css("left",-percentX * mouse_left + "px");
                $(".big-box img").css("top",-percentY * mouse_top + "px")
    
            })
       })
    
    </script>
    </body>
    </html>
    商品放大
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .shade{
                position: fixed;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                background: rgba(0,0,0,.6) ;
                z-index: 20;
            }
            .modal{
                position: fixed;
                left: 50%;
                top: 50%;
                height: 300px;
                width: 400px;
                margin-top: -150px;
                margin-left: -200px;
                z-index: 30;
                border: 1px solid #ddd;
                background-color: white;
            }
            .hide{
                display: none;
            }
            .modal form {
                position: fixed;
                left: 50%;
                top: 50%;
                height: 200px;
                width: 229px;
                border: 1px;
                margin-left: -115px;
                margin-top: -100px;
            }
            .modal form p {
                float: right;
                margin-top: 12px;
            }
            .modal form span {
                float: right;
                display: inline-block;
                height: 18px;
                width: 170px;
                background-color: #FFEBEB;
                text-align: center;
                border: 1px solid #ffbdbe;
                color: #e4393c;
                font-size: 14px;
                visibility: hidden;
            }
            .modal form [type="button"] {
                position: absolute;
                bottom: -30px;
                left: 115px;
            }
            .modal form [value="提交"]{
                left: 50px;
            }
        </style>
    </head>
    <body>
        <div style=" 300px; margin: 0 auto">
            <input type="button" value="添加主机" onclick="return Add();" />
            <table style="border: 2px solid #F5F5F5;  300px;">
                <thead>
                    <tr>
                        <th >主机名</th>
                        <th >IP</th>
                        <th >端口</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td target="host">c1.com</td>
                        <td target="ip">1.1.1.1</td>
                        <td target="port">8888</td>
                        <td onclick="Edit(this);">Edit</td>
                    </tr>
                   <tr>
                        <td target="host">c2.com</td>
                        <td target="ip">1.1.1.1</td>
                        <td target="port">8888</td>
                        <td onclick="Edit(this);">Edit</td>
                    </tr>
                    <tr>
                        <td target="host">c3.com</td>
                        <td target="ip">1.1.1.1</td>
                        <td target="port">8888</td>
                        <td onclick="Edit(this);">Edit</td>
                    </tr>
                    <tr>
                        <td target="host">.com</td>
                        <td target="ip">1.1.1.1</td>
                        <td target="port">8888</td>
                        <td onclick="Edit(this);">Edit</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="shade hide"></div>
        <div  class="modal hide">
            <form action="" method="get">
                <p>主机名:<input type="text" id="host" name="host"><br><span></span></p>
                <p>IP地址:<input type="text" id='ip' name="ip"><br><span></span></p>
                <p>端口号:<input type="text" id='port' name="port"><br><span></span><br></p>
                <input type="button" value="提交" onclick="return SubmitForm();">
                <input type="button" value="取消" onclick="HideModal();">
            </form>
        </div>
    
        <script src="jquery-3.3.1.min.js"></script>
        <script>
            $(function () {
               $("tr:even").css("background-color","#f5f5f5");
            });
            function Edit(ths) {
                $(".shade,.modal").removeClass("hide");
                prevList = $(ths).prevAll();
                prevList.each(function () {
                    var text = $(this).text();
                    var target = $(this).attr("target");
                    $("#"+target).val(text);
                });
            }
            function HideModal() {
                $(".shade,.modal").addClass("hide");
                $(".modal").find("input[type='text']").val("");
                Addd = false;
            }
            function SubmitForm() {
                var flag = Detection();
    
                try {
                        if (Addd && flag){
                        $("tbody").append($("tr").last().clone());
                        $(".modal").find("input[type='text']").each(function () {
                            var value = $(this).val();
                            var name = $(this).attr("name");
                            ($("tr").last().children()).each(function () {
                                if ($(this).attr("target") == name){
                                    $(this).text(value);
                                    return
                                }
                                    }
                            )});
                        Addd = false;
                        HideModal();
                        return false;
                    }
                }catch (e){}
    
    
                if (flag){
                    $(".modal").find("input[type='text']").each(function () {
                        var value = $(this).val();
                        var name = $(this).attr("name");
                        $(prevList).each(function () {
                            if ($(this).attr("target") == name){
                                $(this).text(value);
                                return
                            }
                                }
                        )});
                        $(".modal,.shade").addClass("hide");
                        HideModal();
                    }
                return flag;
                }
    
    
            function Detection() {
                var flag = true;
                $(".modal").find("input[type='text']").each(function () {
                    var value = $(this).val();
                    if (value.length == 0){
                        $(this).next().next().css("visibility","visible").text("亲,不能为空");
                        flag = false;
                        return false;
                    }else {
                        $(this).next().next().css("visibility","hidden").text("");
                    }
    
                    if ($(this).attr('name') == "host"){
                        var r = /(.com)$/;
                        if (r.test(value) == false){
                            $(this).next().next().css("visibility","visible").text("主机名必须以.com结尾");
                            flag = false;
                            return false;
                    }
                    }else if ($(this).attr('name') == "ip"){
                        var r2 = /^(([0-2]?[0-9][0-9]?).){3}([0-2]?[0-9][0-9]?)$/;
                        if (r2.test(value) == false){
                            $(this).next().next().css("visibility","visible").text("ip 地址格式有误");
                            flag = false;
                            return false;
                        }
                    }else if ($(this).attr('name') == "port"){
                        var r3 = /^([0-9]{1,5})$/;
                        if ((r3.test(value) == false) || (value > 65535)){
                            $(this).next().next().css("visibility","visible").text("端口必须为0-65535");
                            flag = false;
                            return false;
                        }
                    }else {
                        $(this).next().next().css("visibility","hidden").text("");
                    }
            });
            return flag;
            }
    
            function Add() {
                Addd = true;
                $(".shade,.modal").removeClass("hide");
            }
        </script>
    </body>
    </html>
    模态框加增加修改数据
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
                padding: 0;
            }
            ul{
                list-style: none;
            }
            .out{
                width: 730px;
                height: 454px;
                margin: 50px auto;
                position: relative;
            }
            .out .img li{
                position: absolute;
                left: 0;
                top: 0;
            }
            .out .num{
                position: absolute;
                left:0;
                bottom: 20px;
                text-align: center;
                font-size: 0;
                width: 100%;
            }
            .out .btn{
                position: absolute;
                top:50%;
                margin-top: -30px;
                width: 30px;
                height: 60px;
                background-color: aliceblue;
                color: black;
                text-align: center;
                line-height: 60px;
                font-size: 40px;
                display: none;
            }
            .out .num li{
                width: 20px;
                height: 20px;
                background-color: black;
                color: #fff;
                text-align: center;
                line-height: 20px;
                border-radius: 60%;
                display: inline;
                font-size: 18px;
                margin: 0 10px;
                cursor: pointer;
            }
            .out .num li.active{
                background-color: red;
            }
            .out .left{
                left: 0;
            }
            .out .right{
                right: 0;
            }
            .out:hover .btn{
                display: block;
                color: white;
                font-weight: 900;
                background-color: black;
                opacity: 0.8;
                cursor: pointer;
            }
            .out img {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>
    <body>
         <div class="out">
             <ul class="img">
                 <li><a href="#"><img src="images/1.jpg" alt=""></a></li>
                 <li><a href="#"><img src="images/2.jpg" alt=""></a></li>
                 <li><a href="#"><img src="images/3.jpg" alt=""></a></li>
                 <li><a href="#"><img src="images/4.jpg" alt=""></a></li>
                 <li><a href="#"><img src="images/5.jpg" alt=""></a></li>
             </ul>
    
             <ul class="num">
                 <!--<li class="active">1</li>-->
                 <!--<li>2</li>-->
                 <!--<li>3</li>-->
                 <!--<li>4</li>-->
                 <!--<li>5</li>-->
             </ul>
    
             <div class="left btn"><</div>
             <div class="right btn">></div>
    
         </div>
    
        <script src="jquery-3.3.1.min.js"></script>
        <script>
    
            $(function(){
                var size=$(".img li").size();
                for (var i= 1;i<=size;i++){
                    var li="<li>"+i+"</li>";
                    $(".num").append(li);
                }
                $(".num li").eq(0).addClass("active");
    
    
                $(".num li").mouseover(function(){
                   $(this).addClass("active").siblings().removeClass("active");
                   var index=$(this).index();
                   i=index;
                   $(".img li").eq(index).fadeIn(1000).siblings().fadeOut(1000);
                });
    
    
            i=0;
            var t=setInterval(move,1500);
    
            function move(){
                i++;
                if(i==size){
                    i=0;
                }
                $(".num li").eq(i).addClass("active").siblings().removeClass("active");
                $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
            }
    
            function moveL(){
                i--;
                if(i==-1){
                    i=size-1;
                }
                $(".num li").eq(i).addClass("active").siblings().removeClass("active");
                $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
            }
    
            $(".out").hover(function(){
                clearInterval(t);
            },function(){
                t=setInterval(move,1500);
            });
    
            $(".out .right").click(function(){
                move()
            });
            $(".out .left").click(function(){
               moveL()
            })
    
            });
        </script>
    
    </body>
    </html>
    轮播图
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
        <style>
            .edit-mode{
                background-color: #b3b3b3;
                padding: 8px;
                text-decoration: none;
                color: white;
            }
            .editing{
                background-color: #f0ad4e;
            }
        </style>
    </head>
    <body>
    
        <div style="padding: 20px">
            <input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全选" />
            <input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反选" />
            <input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />
    
            <a id="edit_mode" class="edit-mode" href="javascript:void(0);"  onclick="EditMode(this, '#tb1');">进入编辑模式</a>
    
        </div>
        <table border="1">
            <thead>
            <tr>
                <th>选择</th>
                <th>主机名</th>
                <th>端口</th>
                <th>状态</th>
            </tr>
            </thead>
            <tbody id="tb1">
                <tr>
                    <td><input type="checkbox" /></td>
                    <td edit="true">v1</td>
                    <td>v11</td>
                    <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td edit="true">v1</td>
                    <td>v11</td>
                    <td edit="true" edit-type="select" sel-val="2" global-key="STATUS">下线</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td edit="true">v1</td>
                    <td>v11</td>
                    <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
                </tr>
            </tbody>
        </table>
    
        <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
        <script>
            /*
             监听是否已经按下control键
             */
            window.globalCtrlKeyPress = false;
    
            window.onkeydown = function(event){
                if(event && event.keyCode == 17){
                    window.globalCtrlKeyPress = true;
                }
            };
            window.onkeyup = function(event){
                if(event && event.keyCode == 17){
                    window.globalCtrlKeyPress = false;
                }
            };
    
            /*
             按下Control,联动表格中正在编辑的select
             */
            function MultiSelect(ths){
                if(window.globalCtrlKeyPress){
                    var index = $(ths).parent().index();
                    var value = $(ths).val();
                    $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                        $(this).parent().parent().children().eq(index).children().val(value);
                    });
                }
            }
        </script>
        <script type="text/javascript">
    
    $(function(){
        BindSingleCheck('#edit_mode', '#tb1');
    });
    
    function BindSingleCheck(mode, tb){
    
        $(tb).find(':checkbox').bind('click', function(){
            var $tr = $(this).parent().parent();
            if($(mode).hasClass('editing')){
                if($(this).prop('checked')){
                    RowIntoEdit($tr);
                }else{
                    RowOutEdit($tr);
                }
            }
        });
    }
    
    function CreateSelect(attrs,csses,option_dict,item_key,item_value,current_val){
        var sel= document.createElement('select');
        $.each(attrs,function(k,v){
            $(sel).attr(k,v);
        });
        $.each(csses,function(k,v){
            $(sel).css(k,v);
        });
        $.each(option_dict,function(k,v){
            var opt1=document.createElement('option');
            var sel_text = v[item_value];
            var sel_value = v[item_key];
    
            if(sel_value==current_val){
                $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).attr('selected',true).appendTo($(sel));
            }else{
                $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).appendTo($(sel));
            }
        });
        return sel;
    }
    
    STATUS = [
        {'id': 1, 'value': "在线"},
        {'id': 2, 'value': "下线"}
    ];
    
    BUSINESS = [
        {'id': 1, 'value': "车上会"},
        {'id': 2, 'value': "二手车"}
    ];
    
    function RowIntoEdit($tr){
        $tr.children().each(function(){
            if($(this).attr('edit') == "true"){
                if($(this).attr('edit-type') == "select"){
                    var select_val = $(this).attr('sel-val');
                    var global_key = $(this).attr('global-key');
                    var selelct_tag = CreateSelect({"onchange": "MultiSelect(this);"}, {}, window[global_key], 'id', 'value', select_val);
                    $(this).html(selelct_tag);
                }else{
                    var orgin_value = $(this).text();
                    var temp = "<input value='"+ orgin_value+"' />";
                    $(this).html(temp);
                }
    
            }
        });
    }
    
    function RowOutEdit($tr){
        $tr.children().each(function(){
            if($(this).attr('edit') == "true"){
                if($(this).attr('edit-type') == "select"){
                    var new_val = $(this).children(':first').val();
                    var new_text = $(this).children(':first').find("option[value='"+new_val+"']").text();
                    $(this).attr('sel-val', new_val);
                    $(this).text(new_text);
                }else{
                    var orgin_value = $(this).children().first().val();
                    $(this).text(orgin_value);
                }
    
            }
        });
    }
    
    function CheckAll(mode, tb){
        if($(mode).hasClass('editing')){
    
            $(tb).children().each(function(){
    
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
    
                }else{
                    check_box.prop('checked',true);
    
                    RowIntoEdit(tr);
                }
            });
    
        }else{
    
            $(tb).find(':checkbox').prop('checked', true);
        }
    }
    
    function CheckReverse(mode, tb){
    
        if($(mode).hasClass('editing')){
    
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    check_box.prop('checked',false);
                    RowOutEdit(tr);
                }else{
                    check_box.prop('checked',true);
                    RowIntoEdit(tr);
                }
            });
    
    
        }else{
    
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    check_box.prop('checked',false);
                }else{
                    check_box.prop('checked',true);
                }
            });
        }
    }
    
    function CheckCancel(mode, tb){
        if($(mode).hasClass('editing')){
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    check_box.prop('checked',false);
                    RowOutEdit(tr);
    
                }else{
    
                }
            });
    
        }else{
            $(tb).find(':checkbox').prop('checked', false);
        }
    }
    
    function EditMode(ths, tb){
        if($(ths).hasClass('editing')){
            $(ths).removeClass('editing');
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    RowOutEdit(tr);
                }else{
    
                }
            });
    
        }else{
    
            $(ths).addClass('editing');
            $(tb).children().each(function(){
                var tr = $(this);
                var check_box = tr.children().first().find(':checkbox');
                if(check_box.prop('checked')){
                    RowIntoEdit(tr);
                }else{
    
                }
            });
    
        }
    }
    
    
        </script>
    
    </body>
    </html>
    编辑加联动

     

  • 相关阅读:
    如何用kaldi做孤立词识别三
    如何用kaldi做孤立词识别二
    脚本注释3
    [转] kaldi中FST的可视化-以yesno为例
    如何用kaldi做孤立词识别-初版
    [转]语言模型训练工具SRILM
    [转]kaldi 神经网络
    [转]kaldi ASR: DNN训练
    [转]Kaldi命令词识别
    [转] 如何用kaldi训练好的模型做特定任务的在线识别
  • 原文地址:https://www.cnblogs.com/Felix-DoubleKing/p/10249195.html
Copyright © 2020-2023  润新知