使用javascript删除表格的行

时间:2017-09-02 09:08:59

标签: javascript jquery

我的示例代码如下:

<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>

在这里,我想删除下一行删除链接的行。

尝试使用'parentNode'并使用currentNode删除child,但没有任何反应。

2 个答案:

答案 0 :(得分:0)

您可以将事件侦听器附加到a以获取单击事件,并使用事件处理程序中的$(this).parents('tr')来访问父行。像这样的东西:

&#13;
&#13;
$('a').on('click', function(e){
e.preventDefault();
$(this).parents('tr').remove();
})
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在这里,您可以使用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

希望有所帮助