如何从JS中的表构建中删除行

时间:2016-09-20 21:31:41

标签: javascript jquery json ajax html5

我从JSON对象构建了一个表,然后从其内容中自动检索它并构建表。然后我添加了一个包含按钮(使用js)的新列,分别删除每一行。我如何根据每个行ID删除某一行?

table.js

$(document).ready(function (){
var json = [
    {
    "id": "0",
    "firstName":"Ahmed",
    "lastName":"Mahmoud",
    "Email": "ahmed.m92@gmail.com",
    "Phone": "0599547632",
    "Type": "Male"},
    {
    "id": "1",
    "firstName":"Mahmoud",
    "lastName":"Qasem",
    "Email": "m.Qasem80@gmail.com",
    "Phone": "0599547632",
    "Type" : "Male"},

    {
    "id": "2",
    "firstName":"Lena",
    "lastName":"Asaed",
    "Email": "lena_ahmed@hotmail.com",
    "Phone": "0599547632",
    "Type": "Female"}
];
        var tr;
        var buttonnode= document.createElement('input');
        for (var i = 0; i < json.length; i++) {
            tr = $('<tr/>');

            tr.append("<td>" + json[i].id +"</td>");
            tr.append("<td >" + json[i].id +"</td>");
            tr.append("<td >" + json[i].firstName +"</td>");
            tr.append("<td >" + json[i].lastName + "</td>");
            tr.append("<td >" + json[i].Email + "</td>");
            tr.append("<td >" + json[i].Phone + "</td>");
            tr.append("<td >" + json[i].Type + "</td>");
            tr.append("<td >"+'<button id="delete" >Delete</button>'+"</td>");
            $('table').append(tr);
        }
    });

enter image description here 这是表格的快照

1 个答案:

答案 0 :(得分:0)

我没有测试过,但你可以这样做:

var table = $("table");

for (var i = 0; i < json.length; i++) {
    var row = "<tr id='row-" + i + "'>";
    row += "<td>" + json[i].id +"</td>";
    row += "<td>" + json[i].firstName +"</td>";
    row += "<td>" + json[i].lastName + "</td>";
    row += "<td>" + json[i].Email + "</td>";
    row += "<td>" + json[i].Phone + "</td>";
    row += "<td>" + json[i].Type + "</td>";
    row += "<td><button onClick='deleteRow(" + i +")'>Delete</button></td>";
    row += "</tr>";
    table.append(row);
}

function deleteRow(rowId){
    table.find("td#row-" + rowId).remove();
}

对于较大的表格,我强烈建议使用像AngularJS这样的框架,这样可以很容易地保持标记简单并实现修改表格的功能。

// edit: if you want to use the original ID of your JSON you can just replace the counter with the JSON objects ID
var row = "<tr id='row-" + json[i].id + "'>";

更新:没有“onclick”的jQuery方式:

$(document).ready(function(){
  var table = $("table");

  for (var i = 0; i < json.length; i++) {
      var row = "<tr id='row-" + i + "'>";
      row += "<td>" + json[i].id +"</td>";
      row += "<td>" + json[i].firstName +"</td>";
      row += "<td>" + json[i].lastName + "</td>";
      row += "<td>" + json[i].Email + "</td>";
      row += "<td>" + json[i].Phone + "</td>";
      row += "<td>" + json[i].Type + "</td>";
      row += "<td><button class='remove-button' data-id='" + i + "'>Delete</button></td>";
      row += "</tr>";
      table.append(row);
  };

  $(".remove-button").click(function(){
    var rowId = $(this).data("id");
    $("#row-" + rowId).remove();
  });
});

JSFiddle