jQuery(*****)

参考1

参考2

1. jQuery
        1. 选择器  $("")
            1. 基本选择器
                1. ID       --> $("#d1")
                2. 标签名   --> $("p")
                3. class名  --> $(".C1")
                4. 通用的   --> $("*")
                5. 组合     --> $(".c1,div,a")
                
            2. 层级选择器
                1. 子子孙孙   --> $("x y")
                2. 儿子选择器 --> $("x>y")
                3. 弟弟选择器 --> $("x~y")
                4. 毗邻选择器 --> $("label+input")

        2. 筛选器
            1. 基本筛选器
                1. :first
                2. :last
                3. :eq()   --> 从0开始
                4. :even   --> 偶数
                5. :odd    --> 奇数
                6. :gt
                7. :lt
                
                8. :not    --> $("div:not(.c1)")
                9. :has    --> $("div:has(.c1)")
                
            2. 属性选择器
                1. $("[title]")
                2. $("[type='text']")
                3. $("[type!='text']")
                
            3. 表单选择器
                1. $(":checkbox")   -->   $("input[type='checkbox']")
                2. $(":text")
                
                ...
            4. 表单对象
                1. $(":disabled")   --> 找到不可用的标签
                
                ...
            5. 筛选器方法(只是应用场景和上面的基本筛选器不同而已)
                1. $("div").first()
                2. ...
            6. 常用的方法
                1. .next()     --> 找到挨着我的下一个同级标签
                2. .nextAll()  --> 下边同级的所有
                3. .nextUntil()--> 往下找,直到找到终止条件为止
                
                4. .prev()
                5. .prevAll()
                6. .prevUntil()
                
                7. .siblings()  --> 找所有的兄弟(前面的后面的都能找到)
                8. .children()
                
                9. .parent()
                10. .parents()
                11. .parentsUntil()
                
                12. .find(各种条件都可以写)
                
        3. 样式操作
            1. 操作class类
                1. .addClass()
                2. .removeClass()
                3. .hasClass()
                4. .toggleClass()
内容概要 
1. 样式操作
        1. 操作class
        2. 操作CSS属性的
            .css("color")
            .css("color", "green")
            .css({"color": "yellow", "border": "1px solid black"})
    2. 位置相关
        1. .offset()    
        2. .position()  --> 相对于定位的父标签的偏移
        
        3. .scrollTop() --> 返回顶部
            $(window).scroll(function(){
              ...
              // 判断窗口距离top有多少
              if ($(window).scrollTop() > 100){
                 // 把返回顶部的按钮显示出来, removeClass("hide");
              }
            })
            
            // 返回顶部的按钮,要做的事儿
            $("返回顶部按钮").click(function(){
               // $(window).scrollTop(0);
            })
        4. .scrollLeft()
        
    3. 尺寸
        1. height
        2. width
        
        3. innerHeight
        4. innerWidth
        
        5. outerHeight
        6. outerWidth
        
    4. 文本操作
        1. .html()   --> 子标签和文本内容
            .html("<a href="...">我是a标签</a>")
        2. .text()   --> 所有的文本内容
        
        3. .val()
            获取用户输入的值
            
            $(":text").val()
            $(":checked").val()  --> 默认返回的都是第一个标签的值
            
            $("#s1").val()       --> select可以直接取选中的值,多选的select返回的是数组格式
            
            $("#t1").val()       --> textarea和input:text类似
    5. 属性操作
        1. .attr()   --> $("a").attr("href")
                         $("a").attr("href", "http://www.sogo.com") 
                         $("a").attr({"href":"http://www.sogo.com", "title": "aaaa"}) 
                         
        2. .prop()   --> 适用于checkbox和radio(返回true或false的属性)
        
内容概要1  
1. jQuery
        1. 查找标签
            1. 选择器
                1. 基本   *****
                2. 层级   *****
                3. 组合   *****
                4. 基本的筛选  *****
                5. 属性  *****
                6. 表单 *****
                7. 上一个 
                8. 下一个
                9. 父标签
                10. 子标签
                11. 兄弟标签

        2. 操作
            1. 创建标签  --> 添加到文档树中
            2. 修改标签(文本,属性,值)
            3. 删除标签
            4. 修改样式
                1. 修改class
                2. 直接修改CSS属性
        3. 补充
            1. .each
                1. $.each([11,22,33,44],function(k,v){
                     console.log(k,v);
                   })
                   
                2. $("div").each(function(){
                     console.log(this);  // 当前循环中的div标签,是一个DOM对象
                   })
            2. .data
                我们可以给任意的jQuery对象保存数据.
                $("body").data("k1", "v1");
                $("body").data("k2", "v2");
                
                $("body").data("k1");
                
                $("body").removeData("k1")  --> 删除k1的值
                
            3. 插件机制(了解即可)
内容概要2 

一、jQuery介绍

1、jQuery是一个轻量级的、兼容多浏览器的JavaScript库。
2、jQuery使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互,能够极大地简化JavaScript编程。它的宗旨就是:“Write less, do more.
3、jQuery相当于Python的第三方模块
  第三方模块其实就是别人写好(封装)的一些代码,我们拿过来用(按照别人定好的规则)
  原生的JS DOM操作是基础
  学习内容: 1. 改变标签  2. 改变标签的属性  3. 改变标签的样式  4. 事件相关

  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的方法
  使用注意事项: 一定要先导入后使用
  基础语法
      $(selector).action()

   HTML对象和jQuery对象的区别
    1. jQuery对象转换成DOM对象,用索引取出具体的标签
    2. DOM对象转换成jQuery对象,$(DOM对象)

  二、查找标签

1、基本选择器

id选择器:         $("#id")
标签选择器:        $("tagName")
class选择器:      $(".className")
所有元素选择器:    $("*")
组合选择器:       $("#id, .className, tagName")
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery初识</title>
</head>
<body>

<div id="d1">d1</div>
<div class="c1">.c1</div>
<p class="c2">p</p>
<a class="c2" href="">a标签</a>

<!--先倒入后使用-->
<script src="jquery-3.2.1.min.js"></script>
</body>
</html>
示例

   

  2、层级选择器

x和y可以为任意选择器

$("x y");     // x的所有后代y(子子孙孙)
$("x > y");  // x的所有儿子y(儿子)
$("x + y")   // 找到所有紧挨在x后面的y
$("x ~ y")   // x之后所有的兄弟y 
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery初识</title>
</head>
<body>

<div id="d1">d1</div>
<div class="c1">.c1</div>
<p class="c2">p</p>
<a class="c2" href="">a标签</a>

<!--筛选器-->
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>


<!--not-->
<div id="d2">
    <p class="c1">div</p>
    <p class="c1">div</p>
    <p class="c2">div</p>
    <p class="c2">div</p>
</div>


<!--:has-->
<div id="d3">
    <div style="background-color: green">
        <p>div中的p标签</p>
    </div>

    <div style="background-color: red">
        <a href="">div中的a标签</a>
    </div>
</div>


<!--属性选择器-->
<form action="" id="f1">
    <label>用户名:
        <input name="username" type="text" disabled>
    </label>

    <label>密码:
        <input name="pwd" type="password">
    </label>


    <label>篮球:
        <input name="hobby" value="basketball" type="checkbox">
    </label>

    <label>足球:
        <input name="hobby" value="football" type="checkbox">
    </label>


    <label><input name="gender" value="1" type="radio">
    </label>

    <label>女:
        <input name="gender" value="0" type="radio">
    </label>

</form>
<script src="jquery-3.2.1.min.js"></script>
</body>
</html>
以下例子所用代码 

3、基本筛选器

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

  

  

    

  4、属性选择器 

[attribute]
[attribute=value]// 属性等于
[attribute!=value]// 属性不等于
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery初识</title>
</head>
<body>

<!--属性选择器-->
<form action="" id="f1">
    <label>用户名:
        <input name="username" type="text" disabled>
    </label>

    <label>密码:
        <input name="pwd" type="password">
    </label>


    <label>篮球:
        <input name="hobby" value="basketball" type="checkbox">
    </label>

    <label>足球:
        <input name="hobby" value="football" type="checkbox">
    </label>


    <label><input name="gender" value="1" type="radio">
    </label>

    <label>女:
        <input name="gender" value="0" type="radio">
    </label>

</form>
<script src="jquery-3.2.1.min.js"></script>
</body>
</html>
View Code

  5、表单筛选器 

:text
:password
:file
:radio
:checkbox

:submit
:reset
:button

例子:

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

表单对象属性:

:enabled
:disabled
:checked
:selected

 例子:

找到可用的input标签

<form>
  <input name="email" disabled="disabled" />
  <input name="id" />
</form>

$("input:enabled")  // 找到可用的input标签

 找到被选中的option:

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

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

三、筛选器方法 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>筛选器示例</title>
</head>
<body>

<ul>
    <li id="l0">l0</li>
    <li>l1</li>
    <li>l2</li>
    <li id="l3">l3</li>
    <li>l4</li>
    <li>l5</li>
</ul>

<!--父标签-->
<div id="d1">div-1
    <div id="d2">div-2
        <div id="d3">div-3
            <a href="">a标签</a>
        </div>
    </div>
</div>

<!--兄弟和儿子-->

<div id="dd">
    <p>p0</p>
    <p>p1</p>
    <p id="p2">p2</p>
    <p>p3</p>
</div>
<script src="jquery-3.2.1.min.js"></script>
</body>
</html>
筛选器示例 

下一个元素:

$("#id").next()
$("#id").nextAll()
$("#id").nextUntil("#i2")  //不包含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() // 索引值等于指定值的元素 
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>样式操作示例</title>
    <style>
        .c1 {
            height: 200px;
             200px;
            border-radius: 50%;
            background-color: red;
            text-align: center;
            padding: 30px 30px;
            font-size: 30px;
        }
        .c2 {
            background-color: green;
        }
    </style>
</head>
<body>

<div class="c1">点我变绿哦</div>

<script src="jquery-3.2.1.min.js"></script>
<script>
    // 找标签
    $("div.c1").click(function () {
        // console.log(this);  // this是DOM对象
        $(this).toggleClass("c2"); // 有就删掉 没有就加上
    })
</script>
</body>
</html>
样式操作示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>左侧菜单栏</title>
    <style>
        .left{
            top:0;
            left:0;
            height: 100%;
            width:20%;
            background-color: rgb(47, 53, 61);
            position: fixed;
        }
        .right{
            width: 80%;
            height: 100%;
        }

        .menu {
            color: white;

        }
        .title{
            text-align:center;
            padding:10px 15px;
            border-bottom:1px solid #23282e;

        }
        .title:hover{
            color:#FF00FF;
        }

        .items{
            background-color: #181c20;
        }

        .item{
            padding: 5px 10px;
            border-bottom:1px solid #23282e;
        }
        .hide{
            display:none;
        }
    </style>
</head>
<body>

</body>
<div class="left">
    <div class="menu">
        <div class="title">菜单一</div>
            <div class="items">
                <div class="item">111</div>
                <div class="item">222</div>
                <div class="item">333</div>
            </div>
        <div class="title">菜单二</div>
        <div class="items hide">
            <div class="item">111</div>
            <div class="item">222</div>
            <div class="item">333</div>
        </div>
        <div class="title">菜单三</div>
        <div class="items hide">
            <div class="item">111</div>
            <div class="item">222</div>
            <div class="item">333</div>
        </div>
    </div>

</div>
<div class="right"></div>

<!--先导入后使用-->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(".title").click(function () {// jQuery绑定事件
        // 找到title标签的下一个标签items,如果没有隐藏就把它隐藏起来,如果被隐藏了就让她显示出来
        $(this).next().toggleClass("hide");//批量操作
        // 隐藏title其它两个兄弟标签
        $(this).next().siblings(".items").addClass("hide");
    });

          // 方式二
    //     $(".menu-title").click(function () {
//        // 1. 找到所有的.menu-items, 隐藏
//        var $currMenuitem = $(this).next();
//        $(".menu-items").not($currMenuitem).addClass("hide");  // 所有的二级菜单都是隐藏的
//        // 2. 找到当前点击菜单下面的.menu-items,把它显示出来(移除hide类)
//        $(this).next().toggleClass("hide");
</script>

</html>
左侧菜单栏示例

 

四、操作标签

1、样式操作

样式类

addClass();        // 添加指定的CSS类名。
removeClass();     // 移除指定的CSS类名。
hasClass();        // 判断样式存不存在
toggleClass();     // 切换CSS类名,如果有就移除,如果没有就添加。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>自定义模态框示例</title>
    <style>
        /*背景铺满整个屏幕*/
        .cover {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background-color: rgba(0,0,0,0.4);
            z-index: 998;
        }
        
        /*模态框*/
        .modal {
            height: 400px;
            width: 600px;
            background-color: white;
            /*居中*/
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -300px;
            margin-top: -200px;
            z-index: 1000;
        }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
<button id="b1">屠龙宝刀,点击就送!</button>
<div class="cover hide"></div>
<div class="modal hide">
    <form>
        <p>
            <label>用户名:
                <input type="text">
            </label>
        </p>
        <p>
            <label>密码:
                <input type="password">
            </label>
        </p>
        <p>
            <input type="submit" value="登录">
            <!--点击取消,模态框关闭-->
            <input id="cancel" type="button" value="取消">
        </p>
    </form>
</div>
<script src="jquery-3.2.1.min.js"></script>
<script>
    // 找到点击弹出模态框的按钮
    $("#b1").click(function () {
        // 把.cover和.modal显示出来(去除掉.hide)
        $(".cover").removeClass("hide");  // 显示背景
        $(".modal").removeClass("hide"); // 显示模态框
    });

    // 找到取消按钮,绑定事件
    $("#cancel").click(function () {
        // 给背景和模态框都加上hide类
        $(".cover").addClass("hide");
        $(".modal").addClass("hide");
    })
</script>
</body>
</html>
自定义模态框

2、修改样式

CSS

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

示例:

$("p").css("color", "red"); //将所有p标签的字体设置为红色
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>修改CSS样式</title>
</head>
<body>

<p>乔小强</p>
<p>二哥</p>
<script src="jquery-3.2.1.min.js"></script>
<script>
    $("p").click(function () {
        // 把当前点击的标签变绿
        // 在处理事件的函数中用 this 表示 当前触发事件的标签
//        $(this).css("color", "red");
//        $(this).css("font-size", "24px");

        $(this).css({"color": "pink", "font-size": "48px"});
    })
</script>
</body>
</html>
修改CSS样式

3、位置操作

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

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

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

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>位置相关方法</title>
    <style>
        /*去除浏览器默认设置的8px的外边距*/
        * {
            margin: 0;
            padding: 0;
        }
        .c1,
        .c2,
        .c3{
            height: 100px;
            width: 100px;
            background-color: red;
            font-size: 20px;
        }
        /*相对定位,相当于原来的位置*/
        .c2 {
            position: relative;
            left: 200px;
            top: 0;
            background-color: green;
        }
        /*绝对定位,相对与定位过的父标签c2*/
        .c3 {
            position: absolute;
            left: 100px;
            top: 100px;
            background-color: blue;
        }
    </style>
</head>
<body>

<div class="c1">我是div</div>
<div class="c2">我是c2
    <div class="c3">我是c3</div>
</div>

<script src="jquery-3.2.1.min.js"></script>
</body>
</html>
位置相关方法

 

<!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>
       * {
           margin: 0;
       }
    .c1 {
      width: 100px;
      height: 200px;
      background-color: red;
    }

    .c2 {
      height: 50px;
      width: 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>
<div class="c3">19</div>
<div class="c3">20</div>
<div class="c3">21</div>
<div class="c3">22</div>
<div class="c3">23</div>
<div class="c3">24</div>
<div class="c3">25</div>
<div class="c3">26</div>
<div class="c3">27</div>
<div class="c3">28</div>
<div class="c3">29</div>
<div class="c3">30</div>
<div class="c3">31</div>




<button id="b2" class="btn btn-default c2 hide">返回顶部</button>
<script src="jquery-3.2.1.min.js"></script>
<script>
  // 设置当滚动条大于80px时候出现hide标签
  $(window).scroll(function () {
    if ($(window).scrollTop() > 80) {
      $("#b2").removeClass("hide");
    }else {
      $("#b2").addClass("hide");
    }
  });
  // 点击b2标签时返回顶部
  $("#b2").click(function () {
    $(window).scrollTop(0);
  })
</script>
</body>
</html>
返回顶部示例

 

 4、尺寸操作 

height()
width()
innerHeight()
innerWidth()
outerHeight()
outerWidth()
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>尺寸示例</title>
    <style>
        .c1 {
            height: 100px;
            width: 200px;
            padding: 10px;
            margin: 20px;
            background-color: red;
            border: 5px solid green;
        }
    </style>
</head>
<body>

<div>
    <div class="c1">div</div>
</div>
<script src="jquery-3.2.1.min.js"></script>
</body>
</html>
尺寸示例

 5、文本操作 

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

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

//值:

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

 

<!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="20" rows="5">

        </textarea>
    </p>
        <p>
            <input id="b1" type="submit" value="登录">
            <input id="cancel" type="button" value="取消">
        </p>
    </form>
<script src="jquery-3.2.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");//这个查找的对象在for中多次用到,所以要提前给它存在一个变量里,防止重复查找增加运算量
        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);
                // 在用户名或密码的下一个标签内(span)添加内容
                $($needEles[i]).next().text( labelName +"不能为空!");
            }
        }
        return false;
    })

</script>
</body>
</html>
文本操作

 6、属性操作

用于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")。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p id="d1">20岁超越30岁,40岁,50岁的人</p>
<p>衣锦还乡</p>
<p>技多不压身</p>

<input type="checkbox" name="hobby" id="i1" checked>读书
<input type="checkbox" name="hobby" id="i2">写字
<input type="checkbox" name="hobby" id="i3">吹牛逼
</body>
</html>
View Code

                 

总结一下:

  1. 对于标签上有的能看到的属性和自定义属性都用attr
  2. 对于返回布尔值的比如checkbox、radio和option的是否被选中都用prop。 
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <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>小强</td>
        <td>相声演员</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>小明</td>
        <td>音乐家</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>韩涉</td>
        <td>导演</td>
    </tr>
    </tbody>
</table>

<input type="button" id="b1" value="全选">
<input type="button" id="b2" value="反选">
<input type="button" id="b3" value="取消">

<script src="jquery-3.2.1.min.js"></script>
<script>
    // 点击全选,表格中所有的checkbox都选中
    // 1. 找checkbox
    // 2. 全部选中  --> prop("checked", true);
    $("#b1").click(function () {
        $(":checkbox").prop("checked", true);
    });

    // 点击取消
    // 1. 找checkbox
    // 2. 全部取消选中  --> prop("checked", false);
   $("#b3").click(function () {
        $(":checkbox").prop("checked", false);
    });

    // 反选
    // 1. 找到所有的checkbox
    // 2. 判断
    // 2.1 原来没选中的,要选中
    // 2.2 原来选中的,要取消选中
       $("#b2").click(function () {
           // 找到所有的checkbox,把它们保存在一个名叫 $checkboxEles 的变量中,方便后面使用
           var $checkboxEles = $(":checkbox");
           // 遍历所有的checkbox,根据每一个checkbox的状态做不同的操作
           for (var i=0;i<$checkboxEles.length;i++){
               // 把每一个checkbox包成jQuery对象
               var $tmp = $($checkboxEles[i]);
               // 如果 checkbox是选中的
               if ($tmp.prop("checked")){
                   // 取消选中
                   $tmp.prop("checked", false);
               }else {
                   // 否则就选中
                   $tmp.prop("checked", true);
               }
           }
    });

</script>
</body>
</html>
exercise-prop 

 7、文档处理 

添加到指定元素内部的后面
  $(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()

 

<!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>1</td>
        <td>小强</td>
        <td>吃冰激凌</td>
        <td>
            <button class="delete">删除</button>
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>二哥</td>
        <td>Girl</td>
        <td>
            <button class="delete">删除</button>
        </td>
    </tr>

    </tbody>
</table>

<button id="b1">添加一行数据</button>
<script src="jquery-3.2.1.min.js"></script>
<script>
    // 绑定事件
    $("#b1").click(function () {
        // 生成要添加的tr标签及数据
        var trEle = document.createElement("tr");
        $(trEle).html("<td>3</td>" +
            "<td>小东北</td>" +
            "<td>社会摇</td>" +
            "<td><button class='delete'>删除</button></td>");
        // 把生成的tr插入到表格中
        $("#t1").find("tbody").append(trEle);
    });
    
    // 每一行的=删除按钮绑定事件
    $(".delete").click(function () {
        // 找到tr标签删除整个标签,相当于删除整行
        $(this).parent().parent().remove();
    });

</script>
</body>
</html>
点击在表格最后一行添加一条数据

                                  

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>替换操作示例</title>
</head>
<body>

<p><a href="http://www.sogo.com">aaa</a></p>
<p><a href="">bbb</a></p>
<p><a href="">ccc</a></p>

<button id="b1">点我!</button>
<script src="jquery-3.2.1.min.js"></script>
<script>
    $("#b1").click(function () {
            // 创建一个img标签
    var imgEle = document.createElement("img");
    $(imgEle).attr("src", "https://img3.duitang.com/uploads/item/201607/22/20160722224001_RyzrQ.jpeg");
    $("a").replaceWith(imgEle);
//    $(imgEle).replaceAll("a");
    });


</script>
</body>
</html>
替换操作示例
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>克隆示例</title>
</head>
<body>

<button id="b1">屠龙宝刀,点我就送!</button>


<script src="jquery-3.2.1.min.js"></script>
<script>
    $("#b1").click(function () {
        $(this).clone().insertAfter(this);
    });
</script>
</body>
</html>
克隆示例

五、事件

1、常用事件

click(function(){...})
hover(function(){...})
blur(function(){...})
focus(function(){...})
change(function(){...})
keyup(function(){...})

2、事件绑定

 (1) 目前为止学过的绑定事件的方式

1. 在标签里面写 onclick=foo(this);
2. 原生DOM的JS绑定 DOM对象.onclick=function(){...}
3. jQuery版的绑定事件 jQuery对象.click(function(){...})

(2)我们今后要用的jQuery绑定事件的方式

.on("click", function(){...})
$("#t1").on("click", "选择器", function(){...})

适用于 给未来的元素(页面生成的时候还没有的标签) 绑定事件 (事件委托)
事件冒泡和事件捕获:
  利用事件冒泡,给已经存在的标签绑定事件,用来捕获后代标签的事件.

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>on绑定事件 点击在表格最后添加一条记录</title>
</head>
<body>
<table border="1" id="t1">
    <thead>
    <tr>
        <th>#</th>
        <th>姓名</th>
        <th>爱好</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>小强</td>
        <td>吃冰激凌</td>
        <td>
            <button class="delete">删除</button>
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>二哥</td>
        <td>Girl</td>
        <td>
            <button class="delete">删除</button>
        </td>
    </tr>

    </tbody>
</table>

<button id="b1">添加一行数据</button>
<script src="jquery-3.2.1.min.js"></script>
<script>
    // 绑定事件
    $("#b1").on("click", function () {
        // 生成要添加的tr标签及数据
        var trEle = document.createElement("tr");
        $(trEle).html("<td>3</td>" +
            "<td>小东北</td>" +
            "<td>社会摇</td>" +
            "<td><button class='delete'>删除</button></td>");
        // 把生成的tr插入到表格中
        $("#t1").find("tbody").append(trEle);
    });
    
    // 每一行的删除按钮绑定事件
    // 在tbody子子孙孙后面只要标签有delete这个类,在点击的时候绑定一个事件
    $("tbody").on("click", ".delete", function () {
        // this指的是点击的那个事件标签
        console.log(this);
        // 找到button的父标签的父标签的父标签tbody删除这个标签
        $(this).parent().parent().remove();
    });

</script>
</body>
</html>
on绑定事件,表格最后一行添加一行记录

3阻止后续事件执行

1、return false; // 常见阻止表单提交等
2、e.preventDefault();
<!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.2.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);
                $($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>
<script src="jquery-3.2.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();
            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>
键盘批量操作

 4、页面载入 

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

两种写法:

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

简写:

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

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

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>页面载入之后执行</title>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        // 等DOM树生成之后 我再执行
        $(document).ready(function () {
            console.log($("#d1").text());
            // 执行绑定事件的操作
        });
    </script>
</head>
<body>

<div id="d1">div标签</div>

</body>
</html>
页面载入之后执行

六、jQuery动画效果 

// 基本
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.2.1.min.js"></script>
<script>
  $("#d1").on("click", function () {
    var newI = document.createElement("i");
    newI.innerText = "+1";
    $(this).append(newI);
    $(this).children("i").animate({
      opacity: 0
    }, 1000)
  })
</script>
</body>
</html>
点赞动画示例

 七、each和data

 1、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是每次循环的具体元素。
})

输出:

0:10
1:20
2:30
3:40

.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循环。

return false

 2、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对应的数据 

八、插件(了解即可)

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

 综合案例:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>周末作业讲解</title>
    <style>
        .cover {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background-color: #616161;
            opacity: 0.4;
            z-index: 998;
        }

        .modal {
            height: 200px;
            width: 300px;
            background-color: white;
            position: absolute;
            margin-top: -100px;
            margin-left: -150px;
            top: 50%;
            left: 50%;
            z-index: 1000;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>

<button id="add">新增</button>
<table border="1">
    <thead>
    <tr>
        <th>#</th>
        <th>姓名</th>
        <th>爱好</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>Egon</td>
        <td>街舞</td>
        <td>
            <button class="edit-btn">编辑</button>
            <button class="delete-btn">删除</button>
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>Alex</td>
        <td>烫头</td>
        <td>
            <button class="edit-btn">编辑</button>
            <button class="delete-btn">删除</button>
        </td>
    </tr>
    <tr>
        <td>3</td>
        <td>苑局</td>
        <td>日天</td>
        <td>
            <button class="edit-btn">编辑</button>
            <button class="delete-btn">删除</button>
        </td>
    </tr>
    </tbody>
</table>

<div id="myCover" class="cover hide"></div>
<div id="myModal" class="modal hide">
    <div>
        <p>
            <label for="modal-name">姓名</label>
            <input type="text" id="modal-name">
        </p>
        <p>
            <label for="modal-hobby">爱好</label>
            <input type="text" id="modal-hobby">
        </p>
        <p>
            <button id="modal-submit">提交</button>
            <button id="modal-cancel">取消</button>
        </p>
    </div>
</div>
<script src="./jquery-3.2.1.min.js"></script>
<script>

    // 定义一个弹出模态框的函数
    function showModal() {
        $("#myCover,#myModal").removeClass("hide");
    }

    // 关闭模态框
    function closeModal() {
        // 1. 清空模态框中的input
        $("#myModal").find("input").val("");
        $("#myCover,#myModal").addClass("hide");
    }

    // 给新增按钮绑定事件
    $("#add").on("click", function () {
        // 把模态框弹出!
//        $("#myCover").removeClass("hide");
//        $("#myModal").removeClass("hide");
        showModal()
    });

    // 模态框中的取消按钮绑定事件
    $("#modal-cancel").on("click", function () {
        // 2. 隐藏模态框
        closeModal();

    });

    // 模态框中的提交按钮绑定事件
    $("#modal-submit").on("click", function () {
        // 1. 取到 用户 填写的 input框的值
        var name = $("#modal-name").val();  // 把用户在模态框里输入的姓名获取到,保存在name变量中
        var hobby = $("#modal-hobby").val();  // 把用户在模态框里输入的爱好获取到,保存在hobby变量中

        var $myModalEle = $("#myModal");
        // 判断,按需操作
        var $currentTrEle = $myModalEle.data("currentTr");
        if ($currentTrEle !== undefined) {
            // 说明是编辑状态
            $currentTrEle.children().eq(1).text(name);
            $currentTrEle.children().eq(2).text(hobby);

            // 清空之前保存的当前行
            $myModalEle.removeData();
        } else {
            // 创建tr标签把数据填进去
            var trEle = document.createElement("tr");
            var number = $("tr").length;
            $(trEle).html("<td>" + number + "</td>" +
                "<td>" + name + "</td>" +
                "<td>" + hobby + "</td>" +
                '<td><button class="edit-btn">编辑</button> <button class="delete-btn">删除</button></td>'
            );
            // 把创建好的tr添加到tbody中
            $("tbody").append(trEle);
        }
        // 隐藏模态框
        closeModal();
    });

    // 2. 根据是编辑 还是新增 做不同的操作
    // 2.1 如果是新增操作,就生成一条新的tr,加到table的最后
    // 2.2 如果是编辑操作, 根据先前 编辑 按钮那一行
    // 难点在于 如何确定 编辑的是哪一行?  --> 利用data()可以存具体的jQuery对象

    // 给每一行的编辑按钮绑定事件
    // 要使用事件委托,基于已经存在的元素(页面加载完之后存在的标签)绑定事件
    $("tbody").on("click", ".edit-btn", function () {
        // 把模态框弹出来
        showModal();
        // 把原来的数据填写到模态框中的input
        var $currentTrEle = $(this).parent().parent();

        // 把当前行的jQuery对象保存起来
        $("#myModal").data("currentTr", $currentTrEle);

        var name = $currentTrEle.children().eq(1).text();
        var hobby = $currentTrEle.children().eq(2).text();

        //
        $("#modal-name").val(name);
        $("#modal-hobby").val(hobby);
    });

    // 给每一行的删除按钮绑定事件
    $("tbody").on("click", ".delete-btn", function () {
        // 删除被点击的删除按钮的那一行
        var $currentTrEle = $(this).parent().parent();
        // 更新序号
        // 找到当前行后面所有的tr,依次更新序号
        $currentTrEle.nextAll().each(function () {
            // 取到原来的序号
            var oldNumber = $(this).children().first().text();
            // 将原来的序号-1,再赋值回去
            $(this).children().first().text(oldNumber - 1);
        });
        $currentTrEle.remove();

    });


</script>
</body>
</html>
大作业

原文地址:https://www.cnblogs.com/zh-xiaoyuan/p/12684852.html