使用jquery动态地向表行追加按钮。

时间:2022-01-18 00:24:32

I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.

我有一个JavaScript JSON对象数组,它正在从JSON格式字符串中解析。现在我要做的就是遍历数组并将数据追加到页面内的一个表中。

jQuery Code:

$.each(objArr, function(key, value) {
  var tr = $("<tr />");
  $.each(value, function(k, v) {
    tr.append($("<td />", {
      html: v
    }));
    $("#dataTable").append(tr);
  })
})

The code works perfectly and the table is getting populated successfully

该代码工作得很好,并且成功地填充了表。

But what I'm looking for is that, I want to add a delete button at the end of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action

但是我想要的是,我想在行的末尾添加一个delete按钮,用户将会删除该行,并且为了执行所需的操作,处理click事件也很重要。

I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:

我用另一种方法做过,但它不是那么有效,我想用上面的代码来完成它,因为它更有效:

for (var i = 0; i < objArr.length; i++) {
  var tr = "<tr>";
  var td1 = "<td>" + objArr[i]["empID"] + "</td>";
  var td2 = "<td>" + objArr[i]["fname"] + "</td>";
  var td3 = "<td>" + objArr[i]["lname"] + "</td>";
  var td4 = "<td>" + objArr[i]["phone"] + "</td>";
  var td5 = "<td>" + objArr[i]["address"] + "</td>";
  var td6 = "<td >" + objArr[i]["deptID"] + "</td>";
  var td7 = "<td>" + objArr[i]["email"] + "</td>";
  var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[
      i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] +
    ')">Delete</button>' + "</td></tr>";
  $("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8);
}

Any suggestions please?

有什么建议吗?

2 个解决方案

#1


1  

Try this, I've include event handler for the each buttons inside the table.

尝试一下,我为表中的每个按钮都包含了事件处理程序。


CHANGES:

变化:

  • Adding Event Listener for each buttons inside the table.
  • 为表中的每个按钮添加事件监听器。
  • Call method (function) with parameters.
  • 调用方法(函数)和参数。

Note: I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.

注意:我正在使用,fadeOut方法只用于退色。你可以看到这些变化。您可以根据需要更改脚本。


EXPLAINS :

解释道:

  • var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
  • var乌鸦= $(这).parents(tr);在这一行中,我们有$(this),这意味着我们已经选择了您已经单击的按钮对象,并使用标记名tr搜索父对象。我们需要这样做,因为我们需要控制tr对象内的所有数据。
  • var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.
  • var cId = $('td:nth-child(2)', cRow).text();在cRow对象上搜索第二个td对象。并从选定的td中获取文本。

JQUERY REFFERENCES :

JQUERY值:


$(document).ready(function() {
  var jsonData = [
    {id: 'A01', name: 'Fadhly'},
    {id: 'A02', name: 'Permata'},
    {id: 'A03', name: 'Haura'},
    {id: 'A04', name: 'Aira'}
  ];

  $.each(jsonData, function(key, val) {
    var tr = '<tr>';
  
    tr += '<td>' + (key + 1) + '</td>';
    tr += '<td>' + val.id + '</td>';
    tr += '<td>' + val.name + '</td>';
  
    tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
  
    tr += '</tr>';
  
    $('tbody').append(tr);
  });
  
  $('button.delete').on('click', function() {
    var cRow = $(this).parents('tr');
    var cId = $('td:nth-child(2)', cRow).text();
    var intKey = $(this).data('key');
    
    cRow.fadeOut('slow', function() {
      doDelete(cId, intKey);
    });
  });
  
  function doDelete(param1, param2) {
    alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table border="1" width="100%">
  <thead>
    <tr>
      <th>#</th>
      <th>Id</th>
      <th>Name</th>
      <th>Action</th>
    </tr>
  </thead>
  
  <tbody>
  </tbody>
</table>

#2


2  

Try something like this:

试试这样:

$.each(objArr, function (key, value) {
                var tr = $("<tr />");
                $.each(value, function (k, v) {
                    tr.append($("<td />", { html: v }));
                    tr.append("<button class='remove' />");
                    $("#dataTable").append(tr);
                })
            })

This shall append the button at the end of the tr with class remove.

这将在tr的末尾添加类删除的按钮。

#1


1  

Try this, I've include event handler for the each buttons inside the table.

尝试一下,我为表中的每个按钮都包含了事件处理程序。


CHANGES:

变化:

  • Adding Event Listener for each buttons inside the table.
  • 为表中的每个按钮添加事件监听器。
  • Call method (function) with parameters.
  • 调用方法(函数)和参数。

Note: I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.

注意:我正在使用,fadeOut方法只用于退色。你可以看到这些变化。您可以根据需要更改脚本。


EXPLAINS :

解释道:

  • var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
  • var乌鸦= $(这).parents(tr);在这一行中,我们有$(this),这意味着我们已经选择了您已经单击的按钮对象,并使用标记名tr搜索父对象。我们需要这样做,因为我们需要控制tr对象内的所有数据。
  • var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.
  • var cId = $('td:nth-child(2)', cRow).text();在cRow对象上搜索第二个td对象。并从选定的td中获取文本。

JQUERY REFFERENCES :

JQUERY值:


$(document).ready(function() {
  var jsonData = [
    {id: 'A01', name: 'Fadhly'},
    {id: 'A02', name: 'Permata'},
    {id: 'A03', name: 'Haura'},
    {id: 'A04', name: 'Aira'}
  ];

  $.each(jsonData, function(key, val) {
    var tr = '<tr>';
  
    tr += '<td>' + (key + 1) + '</td>';
    tr += '<td>' + val.id + '</td>';
    tr += '<td>' + val.name + '</td>';
  
    tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
  
    tr += '</tr>';
  
    $('tbody').append(tr);
  });
  
  $('button.delete').on('click', function() {
    var cRow = $(this).parents('tr');
    var cId = $('td:nth-child(2)', cRow).text();
    var intKey = $(this).data('key');
    
    cRow.fadeOut('slow', function() {
      doDelete(cId, intKey);
    });
  });
  
  function doDelete(param1, param2) {
    alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table border="1" width="100%">
  <thead>
    <tr>
      <th>#</th>
      <th>Id</th>
      <th>Name</th>
      <th>Action</th>
    </tr>
  </thead>
  
  <tbody>
  </tbody>
</table>

#2


2  

Try something like this:

试试这样:

$.each(objArr, function (key, value) {
                var tr = $("<tr />");
                $.each(value, function (k, v) {
                    tr.append($("<td />", { html: v }));
                    tr.append("<button class='remove' />");
                    $("#dataTable").append(tr);
                })
            })

This shall append the button at the end of the tr with class remove.

这将在tr的末尾添加类删除的按钮。