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

How to delete selected table row with javascript or html button?

这里是新手...

如何添加可以删除特定 table 行的函数? 在最后几个小时..我所能做的就是制作一个输出结果,不断删除所有行(不仅仅是1行..它就像清除table中的所有输入)通过使用table.deleteRow( ) 是否通过创建 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. 选择一行时将数据传递到输入。
  2. 单击删除按钮将激活搜索 table 上的输入数据并删除该行的功能。

片段:

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>

您可以使用以下代码,我通过在所选行上设置 class 而不是背景颜色对您的代码进行了一些更改,然后 deselectedRow 在您的情况下毫无用处。

所以发生了什么,点击我添加到行 selected-row class 如果你再次点击它 class 将被删除,然后在“删除选择”按钮上我'我们添加了一个执行 deleteSelections 函数的点击处理程序,它将删除带有 selected-row class.

的所有行

代码如下:

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 > 0 以防止点击 table header