效果示例:
个人的练习代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <style> body{ margin: 0; padding: 0; } .cover{ position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: #b0b0b0; opacity: 0.4; z-index: 2; } .modal{ width: 500px; height: 400px; position: fixed; z-index: 3; background-color: white; left: 50%; top: 40%; margin-left: -250px; margin-top: -200px; } .hide{ display: none; } </style> </head> <body> <div class="cover hide"></div> <div class="modal hide"> <div> <label for="name">姓名</label><input type="text" id="name"> </div> <div> <label for="hobby">爱好</label><input type="text" id="hobby"> </div> <button id="cancel">取消</button> <button id="submit">提交</button> </div> <button id="add">新增</button> <table border="1"> <thead> <tr> <td>#</td> <td>姓名</td> <td>爱好</td> <td colspan="2" style="text-align: center">操作</td> </tr> </thead> <tbody> <tr> <td><input type="checkbox"></td> <td>小明</td> <td id="t1">抽烟,喝酒,烫头</td> <td><button class="move">删除</button></td> <td><button class="edit">编辑</button></td> </tr> <tr> <td><input type="checkbox"></td> <td>贝吉塔</td> <td>修行,找布尔玛吃东西</td> <td><button class="move">删除</button></td> <td><button class="edit">编辑</button></td> </tr> <tr> <td><input type="checkbox"></td> <td>孙悟空</td> <td>吃饭去界王星修炼</td> <td><button class="move">删除</button></td> <td><button class="edit">编辑</button></td> </tr> </tbody> </table> <script> // 新增按钮 $("#add").click(function () { $("#name,#hobby").prop("value",""); $(".cover,.modal").removeClass("hide"); }); // 取消按钮 $("#cancel").click(function () { $(".cover,.modal").addClass("hide"); }); //删除行,用到事件委托,主要是因为新增的行不会自动添加按钮事件 $("tbody").on("click",".move",function () { $(this).parent().parent().remove(); }); //提交 $("#submit").click(function () { var name = $("#name").val(); var hobby = $("#hobby").val(); if($("#submit").data("k")){ bt_edit = $("#submit").data("k"); bt_edit.parent().prev().prev().prev().text(name); bt_edit.parent().prev().prev().text(hobby); }else{ var s = "<tr>" + " <td><input type=\"checkbox\"></td>" + " <td>"+name+"</td>" + " <td>"+hobby+"</td>" + " <td><button class=\"move\">删除</button></td>" + "<td><button>编辑</button></td></tr>"; $("tbody").append(s); } $(".cover,.modal").addClass("hide"); $("#submit").data("k",""); }); //编辑 $("tbody").on("click",".edit",function () { //设定一个标志位 $("#submit").data("k",$(this)); var name = $(this).parent().prev().prev().prev().text(); var hobby = $(this).parent().prev().prev().text(); console.log(name); $("#name").val(name); $("#hobby").val(hobby); $(".cover,.modal").removeClass("hide"); }) </script> </body> </html>
原文地址:https://www.cnblogs.com/robertx/p/10398208.html
时间: 2024-10-09 10:59:15