web前端----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()

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對應的數據

示例:

模態框編輯的數據回填表格

插件(了解即可)

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

例子:

自定義的jQuery登錄驗證插件

<!DOCTYPE html>
<html lang="en">
<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> .login-form { margin: 100px auto 0; max-width: 330px; } .login-form > div { margin: 15px 0; } .error { color: red; } </style>
</head>
<body>


<div>
  <form action="" class="login-form" novalidate>

    <div>
      <label for="username">姓名</label>
      <input id="username" type="text" name="name" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="passwd">密碼</label>
      <input id="passwd" type="password" name="password" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="mobile">手機</label>
      <input id="mobile" type="text" name="mobile" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="where">來自</label>
      <input id="where" type="text" name="where" autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <input type="submit" value="登錄">
    </div>

  </form>
</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="validate.js"></script>
<script> $.validate(); </script>
</body>
</html>
HTML文件
"use strict"; (function ($) { function check() { // 定義一個標志位,表示驗證通過還是驗證不通過 var flag = true; var errMsg; // 校驗規則 $("form input[type!=':submit']").each(function () { var labelName = $(this).prev().text(); var inputName = $(this).attr("name"); var inputValue = $(this).val(); if ($(this).attr("required")) { // 如果是必填項 if (inputValue.length === 0) { // 值為空 errMsg = labelName + "不能為空"; $(this).next().text(errMsg); flag = false; return false; } // 如果是密碼類型,我們就要判斷密碼的長度是否大於6位 if (inputName === "password") { // 除了上面判斷為不為空還要判斷密碼長度是否大於6位 if (inputValue.length < 6) { errMsg = labelName + "必須大於6位"; $(this).next().text(errMsg); flag = false; return false; } } // 如果是手機類型,我們需要判斷手機的格式是否正確 if (inputName === "mobile") { // 使用正則表達式校驗inputValue是否為正確的手機號碼 if (!/^1[345678]\d{9}$/.test(inputValue)) { // 不是有效的手機號碼格式 errMsg = labelName + "格式不正確"; $(this).next().text(errMsg); flag = false; return false; } } } }); return flag; } function clearError(arg) { // 清空之前的錯誤提示 $(arg).next().text(""); } // 上面都是我定義的工具函數 $.extend({ validate: function () { $("form :submit").on("click", function () { return check(); }); $("form :input[type!='submit']").on("focus", function () { clearError(this); }); } }); })(jQuery);
JS文件

 傳參版插件:

<!DOCTYPE html>
<html lang="en">
<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> .login-form { margin: 100px auto 0; max-width: 330px; } .login-form > div { margin: 15px 0; } .error { color: red; } </style>
</head>
<body>


<div>
  <form action="" class="login-form" novalidate>

    <div>
      <label for="username">姓名</label>
      <input id="username" type="text" name="name" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="passwd">密碼</label>
      <input id="passwd" type="password" name="password" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="mobile">手機</label>
      <input id="mobile" type="text" name="mobile" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="where">來自</label>
      <input id="where" type="text" name="where" autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <input type="submit" value="登錄">
    </div>

  </form>
</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="validate3.js"></script>
<script> $.validate({"name":{"required": true}, "password": {"required": true, "minLength": 8}, "mobile": {"required": true}}); </script>
</body>
</html>
HTML文件
"use strict"; (function ($) { function check(arg) { // 定義一個標志位,表示驗證通過還是驗證不通過 var flag = true; var errMsg; // 校驗規則 $("form input[type!=':submit']").each(function () { var labelName = $(this).prev().text(); var inputName = $(this).attr("name"); var inputValue = $(this).val(); if (arg[inputName].required) { // 如果是必填項 if (inputValue.length === 0) { // 值為空 errMsg = labelName + "不能為空"; $(this).next().text(errMsg); flag = false; return false; } // 如果是密碼類型,我們就要判斷密碼的長度是否大於6位 if (inputName === "password") { // 除了上面判斷為不為空還要判斷密碼長度是否大於6位 if (inputValue.length < arg[inputName].minLength) { errMsg = labelName + "必須大於"+arg[inputName].minLength+""; $(this).next().text(errMsg); flag = false; return false; } } // 如果是手機類型,我們需要判斷手機的格式是否正確 if (inputName === "mobile") { // 使用正則表達式校驗inputValue是否為正確的手機號碼 if (!/^1[345678]\d{9}$/.test(inputValue)) { // 不是有效的手機號碼格式 errMsg = labelName + "格式不正確"; $(this).next().text(errMsg); flag = false; return false; } } } }); return flag; } function clearError(arg) { // 清空之前的錯誤提示 $(arg).next().text(""); } // 上面都是我定義的工具函數 $.extend({ validate: function (arg) { $("form :submit").on("click", function () { return check(arg); }); $("form :input[type!='submit']").on("focus", function () { clearError(this); }); } }); })(jQuery);
JS文件

 

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

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

<!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">&times;</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>
增刪改1

第二種:點擊編輯有模態框

<!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>
增刪改2

第三種:基於bootstrap的表格數據編輯+左側菜單欄

<!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">&times;</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>
增刪改3

 補充一個知識點 data

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

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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM