嘿,我是 javascript 的新手,我想了解删除和更新按钮的工作原理。我看到了很多建议,但我的删除按钮似乎不起作用,我不知道哪里出错了。请帮忙
<script type="text/javascript">
function Delete(object){
table = document.getElementById("table");
row = document.getElementById(object);
table.removeChild(row);
};
</script>
<table id="table" class="table .table-bordered" style="width:50%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>DOB</th>
<th>Gender</th>
<th>Martial Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Sara</td>
<td>1-12-1990</td>
<td>Female</td>
<td>Married</td>
<button>Edit</button>
<button onclick="Delete">Delete</button>
</tr>
</tbody>
</table>
还有一个问题是删除按钮显示在表格的顶部而不是在操作列中,为什么?
最佳答案
您需要将元素作为参数传递给 Delete()
.该元素不是 ID,因此您不应使用 getElementById
使用它,只需直接访问元素即可。您可以使用 parentElement
在 DOM 层次结构中向上查找包含的行和表。
解决布局问题,需要把按钮放在<td>
里面.表行中的所有内容都必须在 <td>
中。或 <th>
.
function Delete(object) {
var row = object.parentElement.parentElement;
var table = row.parentElement;
table.removeChild(row);
};
<table id="table" class="table .table-bordered" style="width:50%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>DOB</th>
<th>Gender</th>
<th>Martial Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Sara</td>
<td>1-12-1990</td>
<td>Female</td>
<td>Married</td>
<td><button>Edit</button></td>
<td><button onclick="Delete(this)">Delete</button></td>
</tr>
</tbody>
</table>
关于javascript - 删除按钮javascript的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31263401/