如何使用 javascript 或 html 按钮删除选定的表格行?

Posted

技术标签:

【中文标题】如何使用 javascript 或 html 按钮删除选定的表格行?【英文标题】:How to delete selected table row with javascript or html button? 【发布时间】:2021-12-17 17:06:45 【问题描述】:

这里是新手...

如何添加可以删除特定表格行的函数? 在过去的几个小时里..我所能做的就是制作一个输出结果,通过使用 table.deleteRow() 来不断删除所有行(不仅仅是 1 行.. 它就像清除表中的所有输入),无论是通过创建html 按钮和创建删除功能。

有没有办法我也可以通过在突出显示功能中选择特定行来删除它?

谢谢

var entryButton = document.getElementById('inputButton')
const tbodyEl = document.querySelector("tbody");
var row = 1;

entryButton.addEventListener('click', tableDisplay); 


function tableDisplay (e) 
    e.preventDefault()
var name = document.getElementById('inputName').value;
var amount = document.getElementById('inputAmount').value;
var date = document.getElementById('inputDate').value;
var remarks = document.getElementById('inputRemarks').value;

    if(!name || !amount || !date || !remarks) 
    alert("Please fill all the blanks")
    return;
    

var table = document.getElementById('displayTable');

var newRow = table.insertRow(row);

var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);

cell1.innerHTML= name
cell2.innerHTML= date
cell3.innerHTML= amount
cell4.innerHTML= remarks

selectedRow()
deselectedRow()

row++;



//highlighting the row

function selectedRow()
    var table = document.getElementById('displayTable');
    for (var i=0;i < table.rows.length;i++)
     table.rows[i].onclick= function () 
      if(!this.selected)
       deselectedRow();
       this.origColor=this.style.backgroundColor;
       this.style.backgroundColor='#90EE90';
       this.selected = true;
      
      else
       this.style.backgroundColor=this.origColor;
       this.selected = false;
      
       
    
    
   
   
   function  deselectedRow()
    var table = document.getElementById('displayTable');
    for (var i=0;i < table.rows.length;i++)
      var row = table.rows[i];
      row.style.backgroundColor=this.origColor;
      row.selected = false;
    
   
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
    <link
      href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css"
      rel="stylesheet"
    />
    <link
      href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
    <title>Expense Tracker </title>
  </head>
  <body>
    <h1 class="d-flex justify-content-center mb-5 mt-5">Expense Tracker V2</h1>
    <form class="form d-flex justify-content-center mb-5">
      <span class="fw-bolder m-1"
        >Name: <input class="m-1" id="inputName" type="text"
      /></span>
      <span class="fw-bolder m-1"
        >Date: <input class="m-1" id="inputDate" type="date"
      /></span>
      <span class="fw-bolder m-1"
        >Amount: <input class="m-1" id="inputAmount" type="number"
      /></span>
      <span class="fw-bolder m-1"
        >Remarks <input class="m-1" id="inputRemarks" type="text"
      /></span>
      <button class="m-1" id="inputButton">
        <i class="icon-level-down fs-4"></i>
      </button>
      <!-- How to delete specific row -->
      <button class="m-1" value="Delete Row" submit="delete"> 
        <i class="icon-remove-sign fs-4"></i>
      </button>
    </form>
    <table class="table m-5" id="displayTable">
      <thead>
        <tr>
          <th scope="col">
            <i class="icon-file-text fw-bolder fs-3"></i> Description
          </th>
          <th scope="col"><i class="icon-calendar fw-bolder fs-3"></i> Date</th>
          <th scope="col"><i class="icon-usd fw-bolder fs-3"></i> Amount</th>
          <th scope="col"><i class="icon-pencil fs-3"></i> Remarks</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script src="script.js"></script>
  </body>
</html>

【问题讨论】:

【参考方案1】:

你可以这样做:

    选择行时,将数据传递到输入。 单击删除按钮将激活功能,该功能将在表中搜索输入数据并删除该行。

片段:

var entryButton = document.getElementById('inputButton')
const tbodyEl = document.querySelector("tbody");
var row = 1;

entryButton.addEventListener('click', tableDisplay); 


function tableDisplay (e) 
    e.preventDefault()
var name = document.getElementById('inputName').value;
var amount = document.getElementById('inputAmount').value;
var date = document.getElementById('inputDate').value;
var remarks = document.getElementById('inputRemarks').value;

    if(!name || !amount || !date || !remarks) 
    alert("Please fill all the blanks")
    return;
    

var table = document.getElementById('displayTable');

var newRow = table.insertRow(row);

var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);

cell1.innerHTML= name
cell2.innerHTML= date
cell3.innerHTML= amount
cell4.innerHTML= remarks

selectedRow()
deselectedRow()

row++;



//highlighting the row

function selectedRow()
    var table = document.getElementById('displayTable');
    for (var i=0;i < table.rows.length;i++)
     table.rows[i].onclick= function () 
      if(!this.selected)
       deselectedRow();
       this.origColor=this.style.backgroundColor;
       this.style.backgroundColor='#90EE90';
       this.selected = true;
       // add the data of the selected row on inputs:
       document.querySelector('#inputName').value = this.querySelectorAll('td')[0].textContent;
      
      document.querySelector('#inputDate').value = this.querySelectorAll('td')[1].textContent;
      
       document.querySelector('#inputAmount').value = this.querySelectorAll('td')[2].textContent;
      
      document.querySelector('#inputRemarks').value = this.querySelectorAll('td')[3].textContent;
      
      
      
      
      else
       this.style.backgroundColor=this.origColor;
       this.selected = false;       
      
       
    
    
   
   
   function  deselectedRow()
    var table = document.getElementById('displayTable');
    for (var i=0;i < table.rows.length;i++)
      var row = table.rows[i];
      row.style.backgroundColor=this.origColor;
      row.selected = false;
    
   
   
   function deleteRow() 
     const tRows = document.querySelectorAll('#displayTable tr');
     tRows.forEach(element => 
     
     if (element.querySelectorAll('td')[0] && (
     element.querySelectorAll('td')[0].textContent === document.querySelector('#inputName').value &&
     element.querySelectorAll('td')[1].textContent === document.querySelector('#inputDate').value &&
     element.querySelectorAll('td')[0].textContent === document.querySelector('#inputName').value &&
     element.querySelectorAll('td')[1].textContent === document.querySelector('#inputDate').value )) 
     element.remove();
     
     );
   
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
    <link
      href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css"
      rel="stylesheet"
    />
    <link
      href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
    <title>Expense Tracker </title>
  </head>
  <body>
    <h1 class="d-flex justify-content-center mb-5 mt-5">Expense Tracker V2</h1>
    <form class="form d-flex justify-content-center mb-5">
      <span class="fw-bolder m-1"
        >Name: <input class="m-1" id="inputName" type="text"
      /></span>
      <span class="fw-bolder m-1"
        >Date: <input class="m-1" id="inputDate" type="date"
      /></span>
      <span class="fw-bolder m-1"
        >Amount: <input class="m-1" id="inputAmount" type="number"
      /></span>
      <span class="fw-bolder m-1"
        >Remarks <input class="m-1" id="inputRemarks" type="text"
      /></span>
      <button class="m-1" id="inputButton">
        <i class="icon-level-down fs-4"></i>
      </button>
      <!-- How to delete specific row -->
      <button class="m-1" value="Delete Row" type="button" onclick="deleteRow();"> 
        <i class="icon-remove-sign fs-4"></i>
      </button>
    </form>
    <table class="table m-5" id="displayTable">
      <thead>
        <tr>
          <th scope="col">
            <i class="icon-file-text fw-bolder fs-3"></i> Description
          </th>
          <th scope="col"><i class="icon-calendar fw-bolder fs-3"></i> Date</th>
          <th scope="col"><i class="icon-usd fw-bolder fs-3"></i> Amount</th>
          <th scope="col"><i class="icon-pencil fs-3"></i> Remarks</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script src="script.js"></script>
  </body>
</html>

【讨论】:

【参考方案2】:

您可以使用以下代码,我通过在所选行上设置类而不是背景颜色来更改您的代码,然后 deselectedRow 在您的情况下没用。

所以发生了什么,单击时我添加到行 selected-row 类,如果再次单击它,该类将被删除,然后在“deleteSelection”按钮上我添加了一个执行 deleteSelections 函数的单击处理程序,这将删除所有具有selected-row 类的行。

代码如下:

var entryButton = document.getElementById('inputButton')
const tbodyEl = document.querySelector("tbody");
var row = 1;

entryButton.addEventListener('click', tableDisplay);


function tableDisplay(e) 
  e.preventDefault()
  var name = document.getElementById('inputName').value;
  var amount = document.getElementById('inputAmount').value;
  var date = document.getElementById('inputDate').value;
  var remarks = document.getElementById('inputRemarks').value;

  if (!name || !amount || !date || !remarks) 
    alert("Please fill all the blanks")
    return;
  

  var table = document.getElementById('displayTable');

  var newRow = table.insertRow(row);

  var cell1 = newRow.insertCell(0);
  var cell2 = newRow.insertCell(1);
  var cell3 = newRow.insertCell(2);
  var cell4 = newRow.insertCell(3);

  cell1.innerHTML = name
  cell2.innerHTML = date
  cell3.innerHTML = amount
  cell4.innerHTML = remarks

  selectedRow()

  row++;



//highlighting the row

document.getElementById('deleteSelection').addEventListener('click', deleteSelections);

function deleteSelections() 
    let selectedRows = document.getElementsByClassName("selected-row ");
    while(selectedRows.length > 0)
        selectedRows[0].parentNode.removeChild(selectedRows[0]);
    


function selectedRow() 
  var table = document.getElementById('displayTable');
  for (var i = 0; i < table.rows.length; i++) 
    if (i > 0) 
      table.rows[i].onclick = function() 
        if (!this.selected) 
          this.classList.add('selected-row')
          this.selected = true;
         else 
          this.classList.remove('selected-row')
          this.selected = false;
        

      
    
  
.selected-row 
  background-color: #90EE90;
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
    <link
      href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css"
      rel="stylesheet"
    />
    <link
      href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
    <title>Expense Tracker </title>
  </head>
  <body>
    <h1 class="d-flex justify-content-center mb-5 mt-5">Expense Tracker V2</h1>
    <form class="form d-flex justify-content-center mb-5">
      <span class="fw-bolder m-1"
        >Name: <input class="m-1" id="inputName" type="text"
      /></span>
      <span class="fw-bolder m-1"
        >Date: <input class="m-1" id="inputDate" type="date"
      /></span>
      <span class="fw-bolder m-1"
        >Amount: <input class="m-1" id="inputAmount" type="number"
      /></span>
      <span class="fw-bolder m-1"
        >Remarks <input class="m-1" id="inputRemarks" type="text"
      /></span>
      <button class="m-1" id="inputButton">
        <i class="icon-level-down fs-4"></i>
      </button>
      <!-- How to delete specific row -->
      <button class="m-1" value="Delete Row" submit="delete"> 
        <i class="icon-remove-sign fs-4"></i>
      </button>
      <button type="button" id="deleteSelection"> 
        Delete selected
      </button>
    </form>
    <table class="table m-5" id="displayTable">
      <thead>
        <tr>
          <th scope="col">
            <i class="icon-file-text fw-bolder fs-3"></i> Description
          </th>
          <th scope="col"><i class="icon-calendar fw-bolder fs-3"></i> Date</th>
          <th scope="col"><i class="icon-usd fw-bolder fs-3"></i> Amount</th>
          <th scope="col"><i class="icon-pencil fs-3"></i> Remarks</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script src="script.js"></script>
  </body>
</html>

然后我在 selectedRow 中添加了i &gt; 0 以防止点击表头

【讨论】:

效率更高——但你重写了 OP 的代码……我只是为了让他学习而修复它(: 谢谢先生。我喜欢你如何清理 selectedRows 并且点击变得流畅。与我的代码不同,它不再是错误的。删除按钮功能也是我一直在寻找的答案,我从中学到了!谢谢!

以上是关于如何使用 javascript 或 html 按钮删除选定的表格行?的主要内容,如果未能解决你的问题,请参考以下文章

如何隐藏或集成地理定位权限弹出到按钮(Javascript + HTML)

Javascript/HTML/Puppeteer - 如何访问属性数据绑定中的值(单击按钮)?

如何仅使用 html 或 css 为音频制作切换按钮?

如何使 PHP 或 JavaScript 生成 HTML 表单

使用带有jQuery或Javascript的按键触发“按钮onClick”

如何使用 Javascript 或任何 Javascript 框架创建用于保存图像的按钮?