本文實例講述了JQuery實現動態添加刪除評論的方法。分享給大家供大家參考。具體實現方法如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>添加評論</title> <style type="text/css"> #tbList td,#tbList th{border:1px solid #000;padding:5px;} </style> <script src="jquery-1.6.2.min.js" type="text/javascript"></script> <script type="text/javascript"> var jsonArr = [ { "id": 1, "name": "1劉德華", "eamil": "[email protected]", "gender": "男" }, { "id": 2, "name": "2劉德華", "eamil": "[email protected]", "gender": "女" }, { "id": 3, "name": "3劉德華", "eamil": "[email protected]", "gender": "女" }, { "id": 4, "name": "4郭富城", "eamil": "[email protected]", "gender": "女" }, { "id": 5, "name": "5張學友", "eamil": "[email protected]", "gender": "男" }, { "id": 6, "name": "6孫紅雷", "eamil": "[email protected]", "gender": "男" } ]; function loadData() { var $th = "<tr><th>ID</th><th>姓名</th><th>郵箱</th><th>性別</th><th>操作</th></tr>"; $("#tbList").append($th); //添加表頭 for (var i = 0; i < jsonArr.length; i++) { //最後一列放一個空的內容,給刪除鏈接留位置 var $tr = $("<tr><td>" + jsonArr[i].id + "</td><td>" + jsonArr[i].name + "</td><td>" + jsonArr[i].eamil + "</td><td>" + jsonArr[i].gender + "</td><td></td></tr>"); var $link = $("<a href='javascript:void(0)'>刪除</a>"); $link.click(function () { //注冊刪除事件 $(this).parent().parent().remove(); //刪除當前行 }); $("td:last", $tr).append($link); //添加刪除鏈接 $("#tbList").append($tr); } } $(function () { loadData(); //添加事件 $("#btnAdd").click(function () { var id = $("#txtID").val(); var name = $("#txtName").val(); var email = $("#txtEmail").val(); var gender = $("#txtGender").val(); if ((id == "") || (name == "") || (email == "") || (gender == "")) { alert("請輸入完整的信息"); return; } var $tr = $("<tr><td>" + id + "</td><td>" + name + "</td><td>" + email + "</td><td>" + gender + "</td><td></td></tr>"); var $link = $("<a href='javascript:void(0)'>刪除</a>"); $link.click(function () { $(this).parent().parent().remove(); }); $("td:last", $tr).append($link); $("#tbList").append($tr); }); }); </script> </head> <body> ID:<input type="text" id="txtID" /> 姓名:<input type="text" id="txtName" /> email:<input type="text" id="txtEmail" /> 性別:<input type="text" id="txtGender" /><br /> <input id="btnAdd" type="button" value="添加" /> <br /> <table id="tbList"> </table> </body> </html>希望本文所述對大家的jQuery程序設計有所幫助。