簡體   English   中英

從克隆表行中添加和刪除單元格

[英]Add & Remove Cells from Cloned Table Rows

我正在嘗試創建一個表,我可以根據需要添加和刪除行。 表格本身是使用 PHP 即時創建的,我無法知道每個表格行中有多少個單元格。 到目前為止,我已經能夠成功添加行,但是在按下“X”時如何刪除特定行一直受阻。

我想,如果我可以將一個數字傳遞給“刪除”函數,它可以用來確定要刪除的行。 我一直在嘗試從克隆數據中刪除最終的“td”,並將其替換為包含正確函數參數的“td”。

到目前為止,我嘗試過的一切都沒有奏效。 有什么建議?

HTML

<table class='group'>
  <tr class='group_row_0'>
    <td>Thing 1</td>
    <td>Thing 2</td>
    <td>Thing 3</td>
    <td>Thing 4</td>
    <td>
      <a href='#' class='group_remove' onclick='javascript:removeGroupField(0);'>X</a> <!-- The "0" here needs to be replaced with the new row # -->
    </td>
  </tr>
</table>

<a href='#' class='group_add' onclick='javascript:addGroupField();'>+ Add Row</a>

Javascript:

var row_index = 1;

function addGroupField(){
  var last_row = row_index-1;

  var rowData = $('.group_row_'+last_row).clone();
  rowData.attr('class','group_row_'+row_index);

  $('.group').append(rowData);

  row_index++;
}

您應該嘗試使用 Javascript 正確附加處理程序,而不是使用內聯處理程序。 只需向表中添加一個處理程序,當單擊X時,通過從單擊的按鈕向上導航到要刪除的tr來刪除行:

 $('table.group').on('click', '.group_remove', function() { const tr = this.parentElement.parentElement; tr.remove(); }); $('.add').on('click', function (){ const cloned = $('.group tr:last-child').clone(); $('.group').append(cloned); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class='group'> <tr class='group_row_0'> <td>Thing 1</td> <td>Thing 2</td> <td>Thing 3</td> <td>Thing 4</td> <td> <a href='#' class='group_remove'>X</a> </td> </tr> <tr class='group_row_1'> <td>Thing 1</td> <td>Thing 2</td> <td>Thing 3</td> <td>Thing 4</td> <td> <a href='#' class='group_remove'>X</a> </td> </tr> <tr class='group_row_2'> <td>Thing 1</td> <td>Thing 2</td> <td>Thing 3</td> <td>Thing 4</td> <td> <a href='#' class='group_remove'>X</a> </td> </tr> <tr class='group_row_3'> <td>Thing 1</td> <td>Thing 2</td> <td>Thing 3</td> <td>Thing 4</td> <td> <a href='#' class='group_remove'>X</a> </td> </tr> </table> <div class="add">add row</div>

看起來你正在使用一些 jQuery,所以你可以為 x 嘗試這個。

$(document).on('click', '.group_remove', function(){
    $(this).closest('tr').remove();
});

它的工作原理是向上 DOM 樹查找與被單擊元素最近的 tr 元素(這是特定的 group_remove 類元素)。 然后,該元素以及其中的所有內容都將被刪除。

<?php
      echo "<table border=0 width=100%>
               <tr id='tabRow'></tr>
            </table>";
      echo "<center><button = addcell();>Add</button></center>";
 ?>

腳本

function addcell() 
{
   var row           = document.getElementById("tabRow");
   var nrow          = row.cells.length;    
   var addcell       = row.insertCell(nrow);
   addcell.align     = "right";
   addcell.innerHTML = "<font color=red onclick=deletecell(this)><sup>X</sup></font>Hello World";
}

function deletecell(rmvcell)
{
   document.getElementById("tabRow").deleteCell(rmvcell.cellIndex);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM