1. 程式人生 > >web前端【第十三篇】jQuery擴展和事件

web前端【第十三篇】jQuery擴展和事件

.text .get lap lose remove 沖突 viewport 賦值 edit

一、jQuery事件

常用事件
blur([[data],fn]) 失去焦點
focus([[data],fn]) 獲取焦點( 搜索框例子)
change([[data],fn]) 當select下拉框中的元素發生改變的時候觸發change事件(select例子)
click([[data],fn]) 點擊
dblclick([[data],fn]) 雙擊
scroll([[data],fn]) 滾動
submit([[data],fn]) 提交

不常用事件
error([[data],fn])
focusin([data],fn)
focusout([data],fn)
keydown([[data],fn]) 按下
keypress([[data],fn]) 按鍵
keyup([[data],fn]) 鍵松開
mousedown([[data],fn]) 鼠標按下
mouseenter([[data],fn]) 鼠標移進去
mouseleave([[data],fn]) 鼠標離開:只有鼠標離開被選元素的時候,才會觸發mouseleave事件
mousemove([[data],fn]) 鼠標移動
mouseout([[data],fn]) 鼠標離開:無論鼠標離開被選元素還是任何子元素,都會觸發mouseout事件
mouseover([[data],fn] 鼠標懸停
mouseup([[data],fn]) 鼠標彈起
resize([[data],fn]) 元素窗口發生變化
select([[data],fn])
unload([[data],fn])
補充:
文檔樹加載完之後綁定事件(絕大多數情況下)
第一種:吧script放在後面。
第二種:
$(document).ready(function(){
// 綁定事件的代碼
....
})

簡寫:
$(function($){
// 綁定事件的代碼
....
});
事件練習
focus和blur練習
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>常用事件</title>
</head>
<body>
<input type="text" name="search" value="蘋果手機" data-show ="">
<button>搜索</button>
<select name="" id="s1">
    <option value="gansu">甘肅</option>
    <option value="wuwei">武威</option>
    <option value="dingxi">定西</option>
    <option value="longxi">隴西</option>
    <option value="dalian">大連</option>
</select>
<script src="jquery-3.2.1.min.js"></script>
<script>
//    focus和blur事件
$(document).ready(function () {
    //文檔加載完之後執行下面的代碼
     $(":input").focus(function () {
        var data = $(this).val();
        $(this).val("");
        $(this).attr("data-show", data);

    });
    $(":input").blur(function () {
        $(this).val($(this).attr("data-show"));
    });
    $("#s1").change(function () {
//        當你的下拉框改變的時候就觸發這個事件,就會執行下面的代碼
        console.log($(this).val())
    })
});

</script>
</body>
</html>

  

mouseleave和mouseout練習
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>onmouse事件</title>
    <style>
        .box{
            width: 300%;
            height: 200px;
        }
        .title{
            background: steelblue;
            line-height: 40px;
        }
        .con{
            background: slategray;
            line-height: 30px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="title">onmouse</div>
    <div class="con hide">
        <div><a href="" class="item">你好嗎?</a></div>
        <div><a href="" class="item">我好啊</a></div>
        <div><a href="" class="item">好就好唄</a></div>
    </div>
</div>
<script>
    var ele_title = document.getElementsByClassName(‘title‘)[0];
    var ele_box = document.getElementsByClassName(‘box‘)[0];
    //鼠標指上去的事件
    ele_title.onmouseover = function () {
        this.nextElementSibling.classList.remove(‘hide‘);
    };
    //鼠標移走的事件的兩種方式
//    方式一(推薦)
     ele_box.onmouseleave= function () {
        ele_title.nextElementSibling.classList.add(‘hide‘);
    };
//    方式二
//    ele_title.onmouseout = function () {
//       this.nextElementSibling.classList.add(‘hide‘);
//    }
//    方式一和方式二的區別:
//    不同點
//      onmouseout:不論鼠標指針離開被選元素還是任何子元素,都會觸發onmouseout事件
//      onmouseleave:只有在鼠標指針離開被選元素時,才會觸發onmouseleave事件
//    相同點:都是鼠標移走觸發事件
</script>
</body>
</html>

  

二、jQuery擴展(很重要!!)

1、jQuery擴展語法

把擴展的內容就可以寫到xxxx.js文件了,在主文件中直接導入就行了。

用法1、$.xxx()
$.extend({
"GDP": function () {
console.log("戴小紅花");
}
});
- 給jQuery添加擴展
- $.GDP()

用法2、$("").xxx()
$.fn.extend({
"BJG": function () {
console.log("英語八級就是好!");
}
})
- 給jQuery對象添加擴展
- $(":input").BJG()

2、練習1

  第一步:不完美

extend.js文件

$.extend({
       "GDP":function () {
           foo();
        console.log("帶小紅花")
    }
});
那麽如果這樣定義一個函數,其他的擴展都可以調用這個函數了
這個函數只想在自己調用。不想讓它公共的調用,不讓他起沖突
那麽定義一個私有的。用一個匿名函數
function foo() {
    console.log("英語八級就是牛")
}
$.fn.extend({
    "BJG":function () {
        foo()
        console.log("就這樣吧")
    }
});

  繼續第二步:加上匿名函數

匿名函數:foo方法只想自己用,不想讓別人調用
(function () {
    $.extend({
       "GDP":function () {
           foo();
        console.log("帶小紅花")
    }
});
    function foo() {  函數的內部可以調用,外部就不可以調用了
    console.log("英語八級就是牛")
    }
})();


(function () {
    $.fn.extend({
    "BJG":function () {
        foo2();
        console.log("就這樣吧")
    }
});
    function foo2() {
        console.log("哎哎呀")
    }
})();

  第三步、越趨於完美:既不可以讓別人在外部隨意調用,也可以避免別人修改$

// 如果怕$被別人改,那麽就傳個參數進去
(function (jq) {
    jq.extend({
       "GDP":function () {
           foo();
          console.log("帶小紅花")
       },   //可以擴展多個(加上逗號在寫幾個)
        "SGS":function () {
          console.log("你蛤蟆")
    }
});
    function foo() {
    console.log("英語八級就是牛")
    }
})(jQuery);


(function (jq) {
    jq.fn.extend({
    "BJG":function () {
        foo2();
        console.log("就這樣吧")
    }
});
    function foo2() {
        console.log("哎哎呀")
    }
})(jQuery);

extend.html文件

技術分享圖片

技術分享圖片

3、具體示例練習(登錄校驗)

login.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>作業1</title>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <style>
        .container {
            margin-top: 50px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <form action="" novalidate>
                <div class="form-group">
                    <label for="username">用戶名</label>
                    <input type="text" class="form-control" id="username" placeholder="username">
                    <span id="helpBlock" class="help-block"></span>
                </div>
                <div class="form-group">
                    <label for="Password">密碼</label>
                    <input type="password" class="form-control" id="Password" placeholder="Password">
                    <span id="helpBlock2" class="help-block"></span>
                </div>
                <button type="submit" class="btn btn-default submit">提交</button>
            </form>
        </div>
    </div>
</div>
<!--jQuery導入一定要放到js的上面-->
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script>
//    var span =$("span");
    $(".submit").on("click",function () {
        //先清空狀態
        $("form .form-group").removeClass("has-error");
        $("form span").text("");
        $(":input").each(function () {
            if ($(this).val().length===0){
                var name =  $(this).prev().text();
                $(this).parent().addClass("has-error");
                $(this).next().text(name+"不能為空");
                return false
            }
        });
    return false
    })


</script>
</body>
</html>

  

loginextend.js 文件
// 匿名函數
(function (jq) {  //jq就相當於$
    jq.extend({
        "myValidate": function (form) {
            var formObj = jq(form) ;//賦一個變量,因為我們經常用到  
                      這裏的form參數就指的是在html文件裏面傳進去的"#login",也就是找到的form標簽
            formObj.find(":submit").on("click", function () {
                //先清空狀態
            formObj.find(".form-group").removeClass("has-error");
            formObj.find("span").text("");

                formObj.find(":input").each(function () {
                    if ($(this).val().length === 0) {
                        var name = $(this).prev().text();
                        $(this).parent().addClass("has-error");
                        $(this).next().text(name + "不能為空");
                        return false
                    }
                });
                return false
            });
        }
    })
})(jQuery);

技術分享圖片

技術分享圖片

loginextend2.js 文件

/**
 * Created by Administrator on 2017/10/17.
 */
// 匿名函數
(function (jq) {
    jq.fn.extend({
        "myValidate": function (arg) {
            console.log(this);  //就是當前的.前面的jQuery對象 $("#login")  ----->也就是[form#login]
            var formObj = this;//賦一個變量,因為我們經常用到
            formObj.find(":submit").on("click", function () {
                // this --->提交的submit
                //先清空狀態
            formObj.find(".form-group").removeClass("has-error");
            formObj.find("span").text("");

            //each循環
            var flag = true;  //設置一個標誌位
                // 找到input的屬性[required=true]的,然後設置相關的操作
            formObj.find("input[required=true]").each(function () {
                var inputID = jq(this).attr("id");  //獲取input的id屬性值  "username"
                var minlength = arg[inputID]["min-length"];  //arg[inputID]["min-length"]--->arg["username"]["min-length"]--->得到6
                if ($(this).val().length === 0) {
                    //而這裏的this是當前的input框,和上面的不是同一個
                    var name = $(this).prev().text();
                    $(this).parent().addClass("has-error");
                    $(this).next().text(name + "不能為空");
                    flag =  false;
                    return flag
                }
                if (minlength!==undefined){
                    if (jq(this).val().length<minlength){
                        var name = $(this).prev().text();
                        $(this).parent().addClass("has-error");
                        $(this).next().text(name + "長度太短");
                        flag =  false;
                        return flag
                     }
                }
            });
            return flag
          });
        }
    })
})(jQuery);

三、表格的添加 | 刪除 | 編輯示例

第一種:點擊編輯沒有模態框,是input框編輯修改

//增刪改1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>增刪改</title>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <style>
        .addBtn {
            margin-top: 30px;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-9 col-md-offset-2">
            <!-- Button trigger modal -->
            <button type="button" class="btn btn-primary btn-mg addBtn" data-toggle="modal" data-target="#myModal">
                添加學生的信息
            </button>
            <table class="table table-striped">
                <tbody>
                <tr>
                    <th>姓名</th>
                    <th>年齡</th>
                    <th>性別</th>
                    <th>操作</th>
                </tr>
                <tr>
                    <td  class="col-md-3">六點</td>
                    <td  class="col-md-3">23</td>
                    <td  class="col-md-3">女</td>
                    <td>
                        <button class="btn btn-success editBtn">編輯</button>
                        <button class="btn btn-danger delBtn">刪除</button>
                    </td>
                </tr>
                <tr>
                    <td>時時彩</td>
                    <td>24</td>
                    <td>女</td>
                    <td>
                        <button class="btn btn-success editBtn">編輯</button>
                        <button class="btn btn-danger delBtn">刪除</button>
                    </td>
                </tr>
                <tr>
                    <td>剛強</td>
                    <td>13</td>
                    <td>男</td>
                    <td>
                        <button class="btn btn-success editBtn">編輯</button>
                        <button class="btn btn-danger delBtn">刪除</button>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>


<!-- Modal模態框 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="username">姓名</label>
                        <input type="text" class="form-control item" id="username" placeholder="username">
                    </div>
                    <div class="form-group">
                        <label for="age">年齡</label>
                        <input type="text" class="form-control item" id="age" placeholder="age">
                    </div>
                    <div class="form-group">
                        <label for="gender">性別</label>
                        <input type="text" class="form-control item" id="gender" placeholder="gender">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary queding">確定</button>
            </div>
        </div>
    </div>
</div>
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script>
    //添加信息
    $(".queding").on("click",function () {
        arr=[];
        $(".item").each(function () {
//            console.log($(this).val()) //返回的是input框裏面輸入的內容
            var ele_v = $(this).val();
            arr.push(ele_v); //吧拿到的值添加到數組
        });
        var s =‘<tr><td>‘+arr[0]+‘</td><td>‘+arr[1]+‘</td><td>‘+arr[2]+‘</td><td><button class="btn btn-success editBtn">編輯</button><button class="btn btn-danger delBtn">刪除</button></td></tr>‘;
        $("tbody").append(s);
        $("#myModal").modal("hide")
    });

    //刪除信息
//    方式一
    $("tbody").on("click",".delBtn",function (e) {  //事件委派
        if (e.target.className==‘btn btn-danger delBtn‘){
            //找到要刪除的行
            // console.log(e.target.parentElement.parentElement);
           e.target.parentElement.parentElement.remove()
        }
    });

//    方式二
       $("tbody").on("click",".delBtn",function () {  //事件委派
           $(this).parent().parent().remove()  //這裏的
        });

    //編輯信息

    $("tbody").on("click",".editBtn",function () {
         var tds = $(this).parent().prevAll();
         tds.each(function () {
            $(this).html(‘<input type="text" value=‘+ $(this).text()+ ‘>‘)
        });

        $(this).text("保存");
        $(this).removeClass("btn btn-success editBtn");
        $(this).addClass("btn btn-info saveBtn")
    });

    $("tbody").on("click",".saveBtn",function () {
        var tds = $(this).parent().prevAll();
        console.log(tds);
        tds.each(function (){
//            $(this).text(this.firstElementChild.value);
            $(this).text($(this).children().first().val());
            console.log()
        });
        $(this).text("編輯");
        $(this).removeClass("btn btn-info saveBtn");
        $(this).addClass("btn btn-success editBtn");
    });


</script>
</body>
</html>

  

第二種:點擊編輯有模態框
//增刪改2

<!DOCTYPE html>
<!-- saved from url=(0041)http://v3.bootcss.com/examples/dashboard/ -->
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="http://v3.bootcss.com/favicon.ico">

    <title>Dashboard Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="./Dashboard_files/bootstrap.min.css" rel="stylesheet">

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link href="./Dashboard_files/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="./Dashboard_files/dashboard.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don‘t actually copy these 2 lines! -->
    <!--[if lt IE 9]>
    <script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="Dashboard_files/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    //cdn導入css樣式
    <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]
    <!--<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">-->


    <style>
        .menu {
            margin: 0 -20px;
            border-bottom: 1px solid #336699;
        }

        .head {
            padding: 15px;
        }

        .my-table-tool {
            margin-bottom: 15px;
        }

        .menu .nav-sidebar > li > a {
            padding-right: 40px;
            padding-left: 40px;
        }
    </style>

</head>

<body>

<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                    aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Project name</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Dashboard</a></li>
                <li><a href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Settings</a></li>
                <li><a href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Profile</a></li>
                <li><a href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Help</a></li>
            </ul>
            <form class="navbar-form navbar-right">
                <input type="text" class="form-control" placeholder="Search...">
            </form>
        </div>
    </div>
</nav>
<!--左側菜單-->
<div class="container-fluid">
    <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">

            <div class="menu">
                <div class="head bg-primary">菜單一</div>
                <ul class="nav nav-sidebar">
                    <li class=""><a href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Overview <span
                            class="sr-only">(current)</span></a>
                    </li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Reports</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Analytics</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/#左側菜單.html">Export</a></li>
                </ul>
            </div>

            <div class="menu">
                <div class="head  bg-primary">菜單二</div>
                <ul class="nav nav-sidebar">
                    <li><a href="http://v3.bootcss.com/examples/dashboard/左側菜單.html">Nav item</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/左側菜單.html">Nav item again</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/左側菜單.html">One more nav</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/左側菜單.html">Another nav item</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/左側菜單.html">More navigation</a></li>
                </ul>
            </div>

            <div class="menu">
                <div class="head  bg-primary">菜單三</div>
                <ul class="nav nav-sidebar">
                    <li><a href="http://v3.bootcss.com/examples/dashboard/左側菜單.html">Nav item again</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/左側菜單.html">One more nav</a></li>
                    <li><a href="http://v3.bootcss.com/examples/dashboard/左側菜單.html">Another nav item</a></li>
                </ul>
            </div>
        </div>
    </div>
</div>
<!--表格-->
<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-2">
            <!-- Button trigger modal -->
            <button type="button" class="btn btn-primary btn-mg addBtn" data-toggle="modal" data-target="#myModal">
                添加學生的信息
            </button>
            <table class="table table-striped">
                <thead>
                <tr>
                        <th>學號</th>
                        <th>姓名</th>
                        <th>年齡</th>
                        <th>性別</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td  class="col-md-2">1</td>
                        <td  class="col-md-2">李欣</td>
                        <td  class="col-md-2">23</td>
                        <td  class="col-md-2">女</td>
                        <td>
                            <button class="btn btn-success editBtn">編輯</button>
                            <button class="btn btn-danger delBtn">刪除</button>
                        </td>
                    </tr>
                    <tr>
                        <td>2</td>
                        <td>時時彩</td>
                        <td>24</td>
                        <td>女</td>
                        <td>
                            <button class="btn btn-success editBtn">編輯</button>
                            <button class="btn btn-danger delBtn">刪除</button>
                        </td>
                    </tr>
                    <tr>
                        <td>3</td>
                        <td>剛強</td>
                        <td>13</td>
                        <td>男</td>
                        <td>
                            <button class="btn btn-success editBtn">編輯</button>
                            <button class="btn btn-danger delBtn">刪除</button>
                        </td>
                    </tr>
                    <tr>
                    <td>4</td>
                    <td>杜康</td>
                    <td>25</td>
                    <td>男</td>
                    <td>
                        <button class="btn btn-success editBtn">編輯</button>
                        <button class="btn btn-danger delBtn">刪除</button>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<!--模態框-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">學生信息</h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="modal-username">姓名</label>
                        <input type="text" class="form-control item" id="modal-username" placeholder="username">
                    </div>
                    <div class="form-group">
                        <label for="modal-age">年齡</label>
                        <input type="text" class="form-control item" id="modal-age" placeholder="age">
                    </div>
                    <div class="form-group">
                        <label for="modal-gender">性別</label>
                        <input type="text" class="form-control item" id="modal-gender" placeholder="gender">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
                <button type="button" class="btn btn-primary queding">確定</button>
            </div>
        </div>
    </div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<script src="jquery-3.2.1.min.js"></script>
<!-- Placed at the end of the document so the pages load faster -->
<!--<script src="Dashboard_files/jquery.min.js"></script>-->
<!--<script>window.jQuery || document.write(‘<script src="../../assets/js/vendor/jquery.min.js"><\/script>‘)</script>-->
<!--<script src="Dashboard_files/bootstrap.min.js"></script>-->
<!-- Just to make our placeholder images work. Don‘t actually copy the next line! -->
<script src="Dashboard_files/holder.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="Dashboard_files/ie10-viewport-bug-workaround.js"></script>

<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script>
    //左側菜單
    $(".head").on("click", function () {
        // 兄弟標簽 緊挨著的ul標簽 隱藏  addClass("hide")
        $(this).parent().siblings().children("ul").slideUp();
        // 把自己 緊挨著的ul標簽顯示  removeClass("hide")
//        $(this).next().removeClass("hide");
        $(this).next().slideToggle();
    });

    //刪除按鈕
    $("tbody").on("click","td>.btn-danger",function () {
        $(this).parent().parent().remove()
    });
    //編輯
    $("tbody").on("click",".editBtn",function () {//事件委派
         //彈出模態框
        //alert(123)
        $("#myModal").modal("show");
        //給模態框賦值
        //1、先取值
        var tds = $(this).parent().parent().children();
        var username = tds.eq(1).text();
        var age = tds.eq(2).text();
        var danger = tds.eq(3).text();
        //2、後賦值
        $("#modal-username").val(username);
        $("#modal-age").val(age);
        $("#modal-gender").val(danger);
        //吧tds保存到myModal的data(先把數據保存下來)
        $("#myModal").data("tds",tds);
        console.log(tds);
//        console.log($("#myModal").data("tds"));
        });
        //點擊模態框中的確定按鈕,增加事件
        $(".queding").on("click",function () {
            //1、隱藏模態框
            $("#myModal").modal("hide");
            //2、更新td的值0
            //取值
            var username = $("#modal-username").val();
            var age = $("#modal-age").val();
            var denger = $("#modal-gender").val();
//                賦值
            //拿到你點擊的哪一行
            var tds = $("#myModal").data("tds");
            console.log(tds);
            if (tds === undefined) {
                //因為添加和編輯共用一個模態框,所以先分開判斷一下
                //當tds在模態框中沒有值的時候,就實現添加的功能,如果有數據,就做編輯的功能
                var tr1 = document.createElement("tr");
                //第一個是td的序號
                $(tr1).append("<td>" + $("tbody tr").length+1 + "</td>");
                console.log($("tbody tr").length);
//             第二個是username
                $(tr1).append(‘<td>‘ + username + ‘</td>‘);
                $(tr1).append(‘<td>‘ + age + ‘</td>‘);
                $(tr1).append(‘<td>‘ + denger + ‘</td>‘);
//             最後加按鈕(找到tbody下的第一行,再從第一行中找到td最後一個td,然後克隆)
//
                var s = $("tbody tr:last").find("td").last();
                var ss = s.clone(true);
                $(tr1).append(ss);
                $("tbody").append(tr1);
            } else {
                console.log(tds);   //這裏的tds就是上面用data保存下來的每一列裏面的內容
                tds.eq(1).text(username);
                tds.eq(2).text(age);
                tds.eq(3).text(denger);
                $("#myModal").removeData("tds")
            }
        });
                 //給添加按鈕增加事件
            $(".addBtn").on("click",function () {
                //當點擊添加按鈕的時候把模態框裏面的..內容清空
                $("#myModal :input").val("");
            });
</script>
</body>
</html>

  

補充一個知識點 data

技術分享圖片

- .data()
- .data("key", value) 保存值,value可以是字符串,也可以是數組,也可以是jquery對象
- .data("key") 獲取值(沒有值就返回undefined)
- .removeData() 刪除所有

- .removeData("key") 刪除key對應的value

web前端【第十三篇】jQuery擴展和事件