1. 程式人生 > >使用JQuery動態建立表格

使用JQuery動態建立表格

知識點:
使用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>