使用JQuery动态创建表格

    xiaoxiao2021-03-25  59

    知识点: 使用jq中html()创建元素,append()添加节点,remove()删除节点,类方法:addClass()和removeClass()方法等

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { padding: 0; margin:0; } input { width:100px; height:30px; /*cursor: pointer;*/ /*font:700 14px/30px "simsun";*/ border-radius: 5px; } table { border-collapse: collapse; margin: 10px 0; } table tr { border: 1px solid #ddd; } table td,table th { padding:5px; text-align: center; } table th{ background-color: #8af6ff; } .mask-color { background-color: rgba(0,0,0,0.4); } #mask{ width: 300px; height: 250px; box-shadow: 2px 2px 2px 2px #ccc; position: absolute; left: 50%; top:50%; margin-left: -150px; margin-top: -125px; } #mask h2 { color: #c30230; font-weight: 700; background-color: #ddd; height:20px; line-height: 20px; font-size: 16px; } #mask input { margin: 10px 0; } </style> </head> <body> <div id="wrapper"> <input type="button" value="添加数据"> <table> <thead> <tr> <th>课程名称</th> <th>所属学院</th> <th>已学会</th> </tr> </thead> <tbody> <tr> <td>JAVASCRIPT</td> <td>前端移动开发学院</td> <td class="get">GET</td> </tr> <tr> <td>HTML5</td> <td>前端移动开发学院</td> <td class="get">GET</td> </tr> <tr> <td>CSS3</td> <td>前端移动开发学院</td> <td class="get">GET</td> </tr> <tr> <td>BOOTSTRAP</td> <td>前端移动开发学院</td> <td class="get">GET</td> </tr> </tbody> </table> </div> <div id="mask" style="display: none"> <h2>添加数据 <span style="float: right;margin-right:10px;display: inline-block;width: 10px;height: 20px">X</span></h2> <div> <span>课程名称:</span> <input id="name" type="text" placeholder="请输入课程名称!" style="width: 150px;height: 30px;"> </div> <div> <span>所属学院:</span> <input id="school" type="text" value="JAVA学院" style="width: 150px;height: 30px;"> </div> <div style="text-align: center"> <button style="width: 150px;height: 25px;text-align: center;line-height: 25px;border: 0;">添加</button> </div> </div> </body> <script src="jquery-1.11.1.js"></script> <script> $("input[type='button']").click(function(){ $("#mask").fadeIn(1000); $("body").addClass("mask-color"); }); $("h2 span").click(function(){ $("#mask").fadeOut(1000); $("body").removeClass("mask-color"); }); $("#mask button").click(function(){ var name = $("#name").val(); var school = $("#school").val(); if(name == "" || name == null){ alert("请输入课程名称!"); return; } $("#mask").fadeOut(); $("body").removeClass("mask-color"); var tr = $("<tr></tr>"); //赋值 tr.html('<td>'+name+'</td><td>'+school+'</td><td class="get">GET</td>'); //在房间tbody中 $("tbody").append(tr); //BUG:新产生的tr没有事件绑定 坑!! tr.click(function(){ $(this).remove(); }) $("#name").val(""); }); $(".get").click(function(){ // alert(0); $(this).parent("tr").remove(); }) </script> </html>
    转载请注明原文地址: https://ju.6miu.com/read-13623.html

    最新回复(0)