简体   繁体   English

使用javascript删除表格的行

[英]Delete row of the table using javascript

I have sample code as follows : 我有以下示例代码:

<table id='emailTable'>
<tr id='tablecontent'>
<td>
</td>
<td>
<a ....>delete</a>
</td>
</tr>

<tr id='tablecontent'>
<td>
</td>
<td>

</td>
</tr>

<tr id='tablecontent'>
<td>
</td>
<td>
<a ....>delete</a>
</td>
</tr>

<tr id='tablecontent'>
<td>
</td>
<td>

</td>
</tr>
<table>

Here, I want to delete the row onclick of delete link with the next row. 在这里,我要删除下一行的删除链接的onclick行。

Have tried with 'parentNode' and removechild with currentNode but nothing happens. 曾尝试使用“ parentNode”和使用currentNode的removechild,但没有任何反应。

you can attach an event listener to a for click event and use $(this).parents('tr') inside event handler to access parent row. 你可以将一个事件侦听器, a点击事件,并使用$(this).parents('tr')事件处理中访问父行。 something like this: 像这样的东西:

 $('a').on('click', function(e){ e.preventDefault(); $(this).parents('tr').remove(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id='emailTable'> <tr id='tablecontent'> <td> </td> <td> <a href="">delete</a> </td> </tr> <tr id='tablecontent'> <td> </td> <td> </td> </tr> <tr id='tablecontent'> <td> </td> <td> <a href="">delete</a> </td> </tr> <tr id='tablecontent'> <td> </td> <td> </td> </tr> <table> 

Here you go table row removal using JavaScript: 在这里,您可以使用JavaScript删除表格行:

// get all rows
var rows = document
  .querySelectorAll("#emailTable tr#tablecontent");
// create a find parent function
// since JavaScript do not have $(elem).parent("tr")
// which automatically search a parent or parent of parents that is a <tr>
var findParent = function (node, tagName)
{
   var recursiveSearch = function(node, tagName)
   {
      // you can change the condition as you see fit.
      return node.parentNode.tagName.toLowerCase() == tagName.toLowerCase() ? node.parentNode : recursiveSearch(node.parentNode, tagName);
   };

   // do a recursive search based from passed node if it matches with a given tag name.
   return recursiveSearch(node, tagName);
};

// loop through each row
rows.forEach(function (item)
{
   // find the delete element
   var deleteElem = item.querySelector("td a.delete");

   // if there is an delete element
   if (deleteElem)
   {
       // add event listener
       deleteElem.addEventListener("click", function ()
       {
          // find parent element that is a <tr>
          var row = findParent(this, "tr");
          // remove the row
          row.remove();
       });
   }
});

working fiddle 工作小提琴

hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM