zoukankan      html  css  js  c++  java
  • jQuery那些事

    本文来自https://www.cnblogs.com/liwenzhou/p/8178806.html

    jQuery介绍

    1. jQuery是一个轻量级的、兼容多浏览器的JavaScript库。
    2. jQuery使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互,能够极大地简化JavaScript编程。它的宗旨就是:“Write less, do more.“

    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对象变量的时候在变量名前面加上$:

    jQuery对象转成DOM对象,jquery对象加[0]
    DOM对象转jQuery对象,$(DOM对象)。
    var $variable = jQuery对像
    var variable = DOM对象
    $variable[0]//jQuery对象转成DOM对象
    $("#i1").html();//jQuery对象可以使用jQuery的方法
    $("#i1")[0].innerHTML;// DOM对象使用DOM的方法

    Query基础语法

    查找标签

    基本选择器

    id选择器:

    $("#id")

    标签选择器:

    $("tagName")

    class选择器:

    $(".className")

    配合使用:

    $("div.c1")  // 找到有c1 class类的div标签

    所有元素选择器:

    $("*")

    组合选择器:

    $("#id, .className, tagName")

    层级选择器:

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

    基本筛选器:

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

    实例

    $("div:has(h1)")// 找到所有后代中有h1标签的div标签
    $("div:has(.c1)")// 找到所有后代中有c1样式类的div标签
    $("li:not(.c1)")// 找到所有不包含c1样式类的li标签
    $("li:not(:has(a))")// 找到所有后代中不含a标签的li标签

    属性选择器:

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

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

    表单筛选器

    :text
    :password
    :file
    :radio
    :checkbox

    :submit
    :reset
    :button

    $(":checkbox")  // 找到所有的checkbox

    表单对象属性:
    :enabled
    :disabled
    :checked
    :selected
    例子
    <form>
      <input name="email" disabled="disabled" />
      <input name="id" />
    </form>
    
    $("input:enabled")  // 找到可用的input标签

    <select id="s1">
    <option value="beijing">北京市</option>
    <option value="shanghai">上海市</option>
    <option selected value="guangzhou">广州市</option>
    <option value="shenzhen">深圳市</option>
    </select>

    $(":selected") // 找到所有被选中的option

    筛选器方法

    下一个元素:

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

    上一个元素:

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

    父亲元素:

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

    儿子和兄弟元素:

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

    查找

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

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

    筛选

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

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

    补充:

    .first() // 获取匹配的第一个元素
    .last() // 获取匹配的最后一个元素
    .not() // 从匹配元素的集合中删除与指定表达式匹配的元素
    .has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。
    .eq() // 索引值等于指定值的元素

    操作标签

    样式操作

    样式类

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

    CSS

    css("color","red")//DOM操作:tag.style.color="red"

    例如

    $("p").css("color", "red"); //将所有p标签的字体设置为红色

    位置操作

    offset()// 获取匹配元素在当前窗口的相对偏移或设置元素位置
    position()// 获取匹配元素相对父元素的偏移
    scrollTop()// 获取匹配元素相对滚动条顶部的偏移
    scrollLeft()// 获取匹配元素相对滚动条左侧的偏移

    .offset()方法允许我们检索一个元素相对于文档(document)的当前位置。

    和 .position()的差别在于: .position()是相对于相对于父级元素的位移。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>模态框</title>
        <style>
    
            .cover{
                position: absolute;
                top: 0;
                left: 0;
                height: 100%;
                width: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 998;
            }
            .hide{
                display: none;
            }
            .modal{
                position: absolute;
                width: 400px;
                height: 300px;
                background: white;
                top: 50%;
                left: 50%;
                margin-left: -200px;
                margin-top: -150px;
                z-index: 1000;
            }
        </style>
    </head>
    <body>
    <button id="btn">点击显示</button>
    <div class="cover hide"></div>
    <div class="modal hide">
        <form>
            <input id="btn2" type="button" value="取消" style="">
        </form>
    </div>
    
    <script src="jquery-3.3.1.js"></script>
    <script>
        $("#btn").click(function () {
            // alert(666)
            $("div").removeClass('hide');
        });
    
        $("#btn2").click(function () {
            // alert(666)
            $("div").addClass('hide');
        });
    </script>
    </body>
    </html>
    模态框

    尺寸:

    height()   文本尺寸
    width()  文本尺寸
    innerHeight()  文本尺寸+上下padding
    innerWidth()  文本尺寸+左右padding
    outerHeight()  文本尺寸+上下padding+上下border
    outerWidth()  文本尺寸+左右padding+左右border

    文本操作

    HTML代码:

    html()// 取得第一个匹配元素的html内容
    html(val)// 设置所有匹配元素的html内容

    文本值:

    text()// 取得所有匹配元素的内容
    text(val)// 设置所有匹配元素的内容

    值:

    val()// 取得第一个匹配元素的当前值
    val(val)// 设置所有匹配元素的值
    val([val1, val2])// 设置多选的checkbox、多选select的值

    例子
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form>
        <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>
        <label for="c1"></label>
        <input name="gender" id="c1" type="radio" value="0">
        <label for="c2"></label>
        <input name="gender" id="c2" type="radio" value="1">
    </form>
    <script src="jquery-3.3.1.js"></script>
    <script>
        $("[name='hobby']").val(['basketball', 'football']);
        $("#s1").val(["1", "2"])
    </script>
    </body>
    </html>

    属性操作

    用于ID等或自定义属性:

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

    用于checkbox和radio

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

    注意:

    在1.x及2.x版本的jQuery中使用attr对checkbox进行赋值操作时会出bug,在3.x版本的jQuery中则没有这个问题。为了兼容性,我们在处理checkbox和radio的时候尽量使用特定的prop(),不要使用attr("checked", "checked")。

    <input type="checkbox" value="1">
    <input type="radio" value="2">
    <script>
      $(":checkbox[value='1']").prop("checked", true);
      $(":radio[value='2']").prop("checked", true);
    </script>

    总结一下:

    1. 对于标签上有的能看到的属性和自定义属性都用attr
    2. 对于返回布尔值的比如checkbox、radio和option的是否被选中都用prop。

    文档处理

    添加到指定元素内部的后面

    $(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()// 删除匹配的元素集合中所有的子节点。

    替换 不常用

    replaceWith()
    replaceAll()

    克隆

    clone()// 参数
    clone方法加参数true,克隆标签并且克隆标签带的事件

    事件

    常用事件

    click(function(){...})
    hover(function(){...})  
    hover() 方法规定当鼠标指针悬停在被选元素上时要运行的两个函数。
    语法:$(selector).hover(inFunction,outFunction)
    inFunction 必需。规定 mouseover 事件发生时运行的函数。
    outFunction 可选。规定 mouseout 事件发生时运行的函数。
    blur(function(){...})
    focus(function(){...})
    change(function(){...})
    keyup(function(){...})   键盘按键松开动作
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <table border="1">
        <thead>
        <tr>
            <th>#</th>
            <th>姓名</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td><input type="checkbox"></td>
            <td>a</td>
            <td>
                <select>
                    <option value="1">上线</option>
                    <option value="2">下线</option>
                    <option value="3">停职</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>b</td>
            <td>
                <select>
                    <option value="1">上线</option>
                    <option value="2">下线</option>
                    <option value="3">停职</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>c</td>
            <td>
                <select>
                    <option value="1">上线</option>
                    <option value="2">下线</option>
                    <option value="3">停职</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>d</td>
            <td>
                <select>
                    <option value="1">上线</option>
                    <option value="2">下线</option>
                    <option value="3">停职</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>f</td>
            <td>
                <select>
                    <option value="1">上线</option>
                    <option value="2">下线</option>
                    <option value="3">停职</option>
                </select>
            </td>
        </tr>
        </tbody>
    </table>
    <script src="jquery-3.3.1.js"></script>
    <script>
        // 实现在按下键盘上一个按键时,前面选择对号的所有行,随着一行改变都改变
        var tag=false;
        // 文档绑定监听按键按下的事件
        var $bodyEle=$("body");
        $bodyEle.on('keydown',function (key) {
            // alert(key.keyCode);
            // console.log(key.keyCode);
            // 当按下的时候就知道要实现批量操作
            if(key.keyCode===16){
                tag=true;
                // console.log(tag);
            }
        });
    
        $bodyEle.on('keyup',function (key) {
            // alert(key.keyCode);
            // console.log(key.keyCode);
            // 当按下的时候就知道要实现批量操作
            if(key.keyCode===16){
                tag=false;
                // console.log(tag);
            }
        });
    
        // 当一行的select发生改变时触发的事件
        $("select").on('change',function () {
            // $(this).parent().siblings().first().find(':checked')是jQuery对象,用if判断肯定通过
            // console.log($(this).parent().siblings().first().find(':checkbox').prop('checked'));
            // 判断前面是否打对勾,并且键盘要按着shift
            // console.log($(this));
            if($(this).parent().siblings().first().find(':checkbox').prop('checked')&&tag){
                // console.log(777);
                // 将所有打对勾的都变化
                // console.log($(this).parent().parent().siblings().find('input[type="checkbox"]:checked'));
                // console.log($(this).val());
    
                // 将当前select的value存起来
                var value=$(this).val();
    
                // 找到需要改变的其他标签,这个找到的是input标签
                $changeEles=$(this).parent().parent().siblings().find('input[type="checkbox"]:checked');
                // console.log($changeEles.parent().parent().find('select'));
    
                // 把其他标签改了
                $changeEles.parent().parent().find('select').val(value);
                // $changeEles.find('select option').val(value);
            }
        });
    
    </script>
    </body>
    </html>
    带有键盘操作的批量操作
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <input type="text" id="i1">
    <script src="jquery-3.3.1.js"></script>
    <script>
        /*
      * oninput是HTML5的标准事件
      * 能够检测textarea,input:text,input:password和input:search这几个元素的内容变化,
      * 在内容修改后立即被触发,不像onchange事件需要失去焦点才触发
      * oninput事件在IE9以下版本不支持,需要使用IE特有的onpropertychange事件替代
      * 使用jQuery库的话直接使用on同时绑定这两个事件即可。
      * */
        $("#i1").on("input propertychange",function () {
            alert($(this).val());
        })
    </script>
    </body>
    </html>
    实时监测输入内容


    事件绑定

    1. .on( events [, selector ],function(){})
    • events: 事件
    • selector: 选择器(可选的)
    • function: 事件处理函数

    移除事件

    1. .off( events [, selector ][,function(){}])

    off() 方法移除用 .on()绑定的事件处理程序。

    • events: 事件
    • selector: 选择器(可选的)
    • function: 事件处理函数

    阻止后续事件执行

    1. return false// 常见阻止表单提交等
    2. e.preventDefault();

    注意:

    像click、keydown等DOM中定义的事件,我们都可以使用`.on()`方法来绑定事件,但是`hover`这种jQuery中定义的事件就不能用`.on()`方法来绑定了。

    想使用事件委托的方式绑定hover事件处理函数,可以参照如下代码分两步绑定事件:

    $('ul').on('mouseenter', 'li', function() {//绑定鼠标进入事件
        $(this).addClass('hover');
    });
    $('ul').on('mouseleave', 'li', function() {//绑定鼠标划出事件
        $(this).removeClass('hover');
    });

    阻止事件冒泡

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>阻止事件冒泡</title>
    </head>
    <body>
    <div>
        <p>
            <span>点我</span>
        </p>
    </div>
    <script src="jquery-3.3.1.js"></script>
    <script>
        $("span").click(function (e) {
            alert("span");
            // 组织事件冒泡
            e.stopPropagation();
        });
    
        $("p").click(function () {
            alert("p");
        });
        $("div").click(function () {
            alert("div");
        })
    </script>
    </body>
    </html>

    页面载入

    当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。这是事件模块中最重要的一个函数,因为它可以极大地提高web应用程序的响应速度。

    
    

    两种写法:

    $(document).ready(function(){
    // 在这里写你的JS代码...
    })

    简写:

    $(function(){
    // 你在这里写你的代码
    })

    文档加载完绑定事件,并且阻止默认事件发生:

    <!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>
      <style>
        .error {
          color: red;
        }
      </style>
    </head>
    <body>
    
    <form id="myForm">
      <label for="name">姓名</label>
      <input type="text" id="name">
      <span class="error"></span>
      <label for="passwd">密码</label>
      <input type="password" id="passwd">
      <span class="error"></span>
      <input type="submit" id="modal-submit" value="登录">
    </form>
    
    <script src="jquery-3.2.1.min.js"></script>
    <script src="s7validate.js"></script>
    <script>
      function myValidation() {
        // 多次用到的jQuery对象存储到一个变量,避免重复查询文档树
        var $myForm = $("#myForm");
        $myForm.find(":submit").on("click", function () {
          // 定义一个标志位,记录表单填写是否正常
          var flag = true;
          $myForm.find(":text, :password").each(function () {
            var val = $(this).val();
            if (val.length <= 0 ){
              var labelName = $(this).prev("label").text();
              $(this).next("span").text(labelName + "不能为空");
              flag = false;
            }
          });
          // 表单填写有误就会返回false,阻止submit按钮默认的提交表单事件
          return flag;
        });
        // input输入框获取焦点后移除之前的错误提示信息
        $myForm.find("input[type!='submit']").on("focus", function () {
          $(this).next(".error").text("");
        })
      }
      // 文档树就绪后执行
      $(document).ready(function () {
        myValidation();
      });
    </script>
    </body>
    </html>
    
    登录校验示例

    与window.onload的区别

    • window.onload()函数有覆盖现象,必须等待着图片资源加载完成之后才能调用
    • jQuery的这个入口函数没有函数覆盖现象,文档加载完成之后就可以调用(建议使用此函数)

    事件委托

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

    示例:

    表格中每一行的编辑和删除按钮都能触发相应的事件。

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

    动画效果

    // 基本
    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]])
    fadeToggle([s,[e],[fn]])
    // 自定义(了解即可)
    animate(p,[s],[e],[fn])
    <!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>
      <style>
        div {
          position: relative;
          display: inline-block;
        }
        div>i {
          display: inline-block;
          color: red;
          position: absolute;
          right: -16px;
          top: -5px;
          opacity: 1;
        }
      </style>
    </head>
    <body>
    
    <div id="d1">点赞</div>
    <script src="jquery-3.3.1.js"></script>
    <script>
      $("#d1").on("click", function () {
        var newI = document.createElement("i");
        newI.innerText = "+1";
        $(this).append(newI);
        // 自定义动画,将i标签透明度设置为0,点击一下,显示一下i标签,然后消失的效果
        $(this).children("i").animate({
          opacity: 0
        }, 1000)
        
      })
    </script>
    </body>
    </html>
    
    点赞特效简单示例
    自定义动画之点赞效果

    补充

    each

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

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

    li =[10,20,30,40]
    $.each(li,function(i, v){
      console.log(i, v);//index是索引,ele是每次循环的具体元素。
    })

    输出:

    010
    120
    230
    340

    .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;

    .data()

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

    .data(key, value):

    描述:在匹配的元素上存储任意相关数据。

    $("div").data("k",100);//给所有div标签都保存一个名为k,值为100

    .data(key):

    描述: 返回匹配的元素集合中的第一个元素的给定名称的数据存储的值—通过 .data(name, value)HTML5 data-*属性设置。

    $("div").data("k");//返回第一个div标签中保存的"k"的值

    .removeData(key):

    描述:移除存放在元素上的数据,不加key参数表示移除所有保存的数据。

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

    示例:

    增删改查

    <!--序号地方需要优化-->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .shadow{
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: #999999;
                opacity: 0.5;
            }
            .mid{
                position: absolute;
                top: 50%;
                left: 50%;
                background-color: white;
                width: 300px;
                height: 200px;
                margin-left: -150px;
                margin-top: -100px
            }
            .hide{
                display: none;
            }
        </style>
    </head>
    <body>
    <input type="text" id="test" value="66666">
    <!--搞一个表格,实现编辑,添加删除功能。点击编辑和添加出现模态框-->
    <input type="button" value="新增" id="add">
    
    <table border="1">  
        <thead>    
        <tr>      
            <th>#</th>
            <th class="name">姓名</th>
            <th class="hobby">爱好</th>
            <th>操作</th>    
        </tr>  
        </thead> 
        <tbody>   
        <tr>      
            <td>1</td>
            <td class="name">张三</td>
            <td class="hobby">打球</td>
            <td><button class="edit">编辑</button><button class="del">删除</button></td>    
        </tr> 
        <tr>      
            <td>2</td>
            <td class="name">李四</td>
            <td class="hobby">打牌</td>
            <td><button class="edit">编辑</button><button class="del">删除</button></td>    
        </tr>
        <tr>      
            <td>3</td>
            <td class="name">王五</td>
            <td class="hobby">扣手机</td>
            <td><button class="edit">编辑</button><button class="del">删除</button></td>    
        </tr>
        </tbody>
    </table>
    <div class="shadow hide"></div>
    <div class="mid hide">
        <p>姓名:<input type="text" id="name"></p>
        <p>爱好:<input type="text" id="hobby"></p>
        <input type="button" value="提交" id="submit">
        <input type="button" value="取消" id="cancel">
    </div>
    <script src="jquery-3.3.1.js"></script>
    <script>
        // 为每一个tr绑定data
        // console.log($("tbody>tr"));
        // $("tbody>tr").each(function () {
        //    // console.log($(this));
        //     $(this).data('k',$(this));
        // });
    
        // 设置标注位,判断是新增还是编辑
        var add;
        var $data;
        // 为取消按钮绑定事件
        $("#cancel").on('click',function () {
                            // 清空已经存在的值
            $("#name").val('');
            $("#hobby").val('');
            // 添加.hide
            $(".shadow").addClass('hide');
            $(".mid").addClass('hide');
    
        })
    
        // 为添加按钮绑定事件
        $("#add").on('click',function () {
    
            // 移除两个div的hide类
            // alert(6666);
            $(".shadow").removeClass('hide');
            $(".mid").removeClass('hide');
            add=true;
        })
        $("#test").on('click',function () {
            // $("#test").text('666');
        })
    
        // 编辑按钮
        $(".edit").on('click',function () {
            // console.log(this);
            $(".shadow").removeClass('hide');
            $(".mid").removeClass('hide');
            $name=$(this).parent().siblings().filter('.name').text();
            $hobby=$(this).parent().siblings().filter('.hobby').text();
            // console.log($name);
            $("#name").val($name);
            $("#hobby").val($hobby);
            $data=$(this).parent().parent().data('k',$(this).parent().parent());
            // console.log($(this).parent().parent().data('k'));
            add=false;
        })
    
        // 删除按钮
        $(".del").on('click',function () {
            $(this).parent().parent().remove();
        })
    
        // 提交按钮
        $("#submit").on('click',function () {
            // 分为新增和编辑两种情况
            if ($("#name").val()!='' && $("#hobby").val()!=''){
                // alert(add);
                // 如果是添加
                if(add===true){
                    // $cloneEle=$("tbody>tr").last().clone(true);
                    // console.log($cloneEle);
                    // // $cloneEle.children()
                    // console.log(this)
                    // 新生成一行数据
                    var trEle=document.createElement('tr');
                    var tdEle=document.createElement('td');
                    var tdEleName=document.createElement('td');
                    $(tdEleName).text($("#name").val());
                    $(tdEleName).attr('class','name');
                    var tdEleHobby=document.createElement('td');
                    $(tdEleHobby).text($("#hobby").val());
                    $(tdEleHobby).attr('class','hobby');
                    var $tdEleDeal=$("tbody>tr").last().find('td').last().clone(true);
                    // console.log($("tbody>tr").last().find('td').last().clone())
                    trEle.append(tdEle);
                    trEle.append(tdEleName);
                    trEle.append(tdEleHobby);
                    trEle.append($tdEleDeal[0]);
                    // console.log(trEle);
                    $("tbody").append(trEle);
    
                }
                // 如果是编辑
                else{
                    // console.log($data);
    
                    // data=$data[0];
                    console.log($data.children());
                    $data.children('[class="name"]').text($("#name").val());
                    $data.children('[class="hobby"]').text($("#hobby").val());
    
                }
                    $(".shadow").addClass('hide');
                    $(".mid").addClass('hide');
    
            }
        })
    </script>
    </body>
    </html>
    实例

    插件(了解即可)

    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>
    复制代码

    单独写在文件中的扩展:

    复制代码
    (function(jq){
      jq.extend({
        funcName:function(){
        ...
        },
      });
    })(jQuery);
    复制代码
    写出漂亮的博客就是为了以后看着更方便的。
  • 相关阅读:
    HTB-靶机-Charon
    第一篇Active Directory疑难解答概述(1)
    Outlook Web App 客户端超时设置
    【Troubleshooting Case】Exchange Server 组件状态应用排错?
    【Troubleshooting Case】Unable to delete Exchange database?
    Exchange Server 2007的即将生命周期,您的计划是?
    "the hypervisor is not running" 故障
    Exchange 2016 体系结构
    USB PE
    10 months then free? 10个月,然后自由
  • 原文地址:https://www.cnblogs.com/zhaowei5/p/10190021.html
Copyright © 2011-2022 走看看