【问题标题】:Trying to remove the whole table row html javascript试图删除整个表格行 html javascript
【发布时间】:2022-06-23 01:44:18
【问题描述】:

JAVASCRIPT

function takeOut(el) {
el.parentElement.remove();
}

document.getElementById('myButton').onclick = function () {
const name = document.getElementById('name').value;
const date = document.getElementById('date').value;
const amount = document.getElementById('amount').value;
const nameTd = '<td>' + name + '</td>';
const dateTd = '<td>' + date + '</td>';
const amountTd = '<td>' + '$'+ amount + '</td>' + '<td>' + 
'<button id="removeBtn"type="button" onClick="takeOut(this)">X</button></td>';
const tr = '<tr>' + nameTd + dateTd +  amountTd + '</tr>';
document.getElementById('table').insertAdjacentHTML('beforeend', tr);
document.getElementById('clearList').onclick = function () {
    const cl = document.getElementById('table');
    while (cl.hasChildNodes()) {
        cl.removeChild(cl.firstChild);
    }
}
document.getElementById('name').value = '';
document.getElementById('amount').value = '';
document.getElementById('date').value = '';
}    

HTML

<!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">
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<h3>Add A New Item:</h3>
<label>Name: <input text="text" id="name"></label><br>
<label>Date:<input type="date" id="date"></label><br>
<label>Amount:<input text="text" id="amount"></label><br>
<button type="button" id="myButton">Add Expense</button>
<button type="button" id="clearList">Clear List</button>
<br>
<br>
<br>
<br>
<br>
<table border="1">
    <tr>
        <th>Name</th>
        <th>Date</th>
        <th>Amount</th>
        <th>Remove</th>
    </tr>
    <tbody  id="table">

    </tbody>
</table>


<script src="script2.js"></script>
</body>
</html>

嘿,所以我试图让带有 x 的按钮删除其所在的整个元素,因此在用户输入费用后,他们可以删除某个元素。每次我单击按钮时,它只会删除实际按钮而不是整个输入。

【问题讨论】:

    标签: javascript html jquery css dom


    【解决方案1】:

    它实际上移除了拥有按钮的父元素。但这是一个td 元素。你想删除 grandparent,所以这样做:

    el.parentElement.parentElement.remove();
    

    只查找最近的tr 元素(在祖先元素中)可能更容易:

    el.closest("tr").remove();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      相关资源
      最近更新 更多