单击删除按钮时如何删除该行?

How to i remove the row when i click delete button?

const Form = document.querySelector(".tracker-form"),
      Name = document.querySelector(".tracker-name"),
      Date = document.querySelector(".tracker-date"),
      Amount = document.querySelector(".tracker-amount"),
      Table = document.querySelector(".tracker-table"),
      tableRow = document.createElement("tr");

      
function deleteRow(event) {
    const button = event.target;
    const row = button.parentNode;

    tableRow.removeChild(row);
}

function addExpense() {
    Form.addEventListener("submit", event => {
        const tableName = document.createElement("td");
        const tableDate = document.createElement("td");
        const tableAmount = document.createElement("td");

        const delButton = document.createElement("button"); 
        delButton.innerHTML = "X";
        delButton.addEventListener("click", deleteRow);
        
        Table.appendChild(tableRow);

        tableRow.appendChild(tableName);
        tableRow.appendChild(tableDate);
        tableRow.appendChild(tableAmount);
        tableRow.appendChild(delButton);
        tableName.innerHTML = Name.value;
        tableDate.innerHTML = Date.value;
        tableAmount.innerHTML = Amount.value;

        Name.value = "";
        Date.value = "";
        Amount.value = "";

        event.preventDefault();
    })
}

function init() {
    addExpense();
}

init();

我正在制作费用跟踪器。当我在名称、日期、金额、值中输入一个值时,每个 table 上都会显示 'x' 按钮。我想在单击 'x' 按钮时删除一行。但它不起作用。谁能告诉我为什么?

您可以简单地删除最近的 tr 元素:

function deleteRow(event) {
  event.target.closest('tr').remove();
}

你需要区分parentNode.

parentNode: The parentNode property returns the parent node of the specified node, as a Node object.

closest

The closest() method searches up the DOM tree for the closest element which matches a specified CSS selector

$(".deleteRowButton").on("click", function(event){
   var $closest = event.target.closest('tr');
   var $parentNode = event.target.parentNode; // It just return `td` instead. 
   console.log({closest: $closest, parentNode: $parentNode});
   $closest.remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr><td>foo</td>
     <td><a class="deleteRowButton">delete_row</a></td></tr>
    <tr><td>bar bar</td>
    <td><a class="deleteRowButton">delete_row</a></td></tr>
    <tr><td>bazmati</td>
     <td><a class="deleteRowButton">delete_row</a></td></tr>
  </table>

可视化输出如下: