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

 

 

posted @ 2018-03-18 21:24  TheLand  阅读(1613)  评论(0编辑  收藏  举报