This article describes the method of JQuery to dynamically add and delete comments. Share it for your reference. The specific implementation method is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/"> <html xmlns="http:///1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Add a comment</title> <style type="text/css"> #tbList td,#tbList th{border:1px solid #000;padding:5px;} </style> <script src="jquery-1.6." type="text/javascript"></script> <script type="text/javascript"> var jsonArr = [ { "id": 1, "name": "1 Andy Lau", "eamil": "123@", "gender": "male" }, { "id": 2, "name": "2 Andy Lau", "eamil": "123@", "gender": "female" }, { "id": 3, "name": "3 Andy Lau", "eamil": "133@", "gender": "female" }, { "id": 4, "name": "4 Aaron Kwok", "eamil": "113@", "gender": "female" }, { "id": 5, "name": "5 Jacky Cheung", "eamil": "223@", "gender": "male" }, { "id": 6, "name": "6 Sun Honglei", "eamil": "423@", "gender": "male" } ]; function loadData() { var $th = "<tr><th>ID</th><th>Name</th><th>Email</th><th>Gender</th><th>Operation</th></tr>"; $("#tbList").append($th); //Add the table header for (var i = 0; i < ; i++) { //The last column puts an empty content, leaving a location for the deleted link 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)'>delete</a>"); $(function () { //Register Delete Event $(this).parent().parent().remove(); //Delete the current line }); $("td:last", $tr).append($link); //Add to delete link $("#tbList").append($tr); } } $(function () { loadData(); //Add event $("#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("Please enter complete information"); 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)'>delete</a>"); $(function () { $(this).parent().parent().remove(); }); $("td:last", $tr).append($link); $("#tbList").append($tr); }); }); </script> </head> <body> ID:<input type="text" /> Name:<input type="text" /> email:<input type="text" /> gender:<input type="text" /><br /> <input type="button" value="Add to" /> <br /> <table > </table> </body> </html>
I hope this article will be helpful to everyone's jQuery programming.