[英]How to delete a row in the table when I click on a button? Using Javascript
[英]This will only delete the first row in my table. I would like it to delete whichever row I click on using jQuery & html
我想知道如何删除我单击删除链接的任何表行。现在,它仅删除一行。
<script type="text/javascript">
$(function() {
$("#deleteEvent").click(function(e) {
$("#drow").remove();
return false;
});
</script>
html在这里
<div id="students">
<table>
<caption>Students</caption>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Student ID</th>
<th>Email</th>
<th>Action</th>
</tr>
<tr id="drow"><td>John</td><td>Doe</td><td>1234</td><td>john.doe@gmail.com</td><td><a href="#" id="deleteEvent">Delete</a></td></tr>
<tr id="drow"><td>Amy</td><td>Adams</td><td>234234</td><td>amy.adams@hotmail.com</td> <td><a href="#" id="deleteEvent">Delete</a></td></tr>
<tr id="drow"><td>Megan</td><td>Huffman</td><td>12255</td><td>amy.adams@hotmail.com</td><td><a href="#" id="deleteEvent">Delete</a></td></tr>
</table>
<a href="#" class="addRecord">Add Record</a>
</div>
您正在HTML中重新使用id
值,这是无效的。 鉴于此,选择这些id
的任何行为都是不确定的。 例如:
$("#drow").remove();
它可能会删除第一个#drow
,可能会删除所有#drow
,可能不会删除所有这些,可能会引发错误,等等。由于标记无效,因此行为未定义。
因此,您要做的第一件事就是不要在HTML中重复使用id
值。 您显示的HTML可以改用class
值:
<tr class="drow">
或者,您可能根本不需要id
或class
...
如果删除按钮在行内,那么您可以相对于使用此按钮单击的按钮引用行:
$(this).closest('tr').remove();
这将从调用事件的元素开始,然后向上遍历DOM,直到找到第一个tr
元素,然后删除该元素。
编辑:您还在a
标记上使用重复的id
:
<a href="#" id="deleteEvent">
您可以将它们替换为一个class
:
<a href="#" class="deleteEvent">
并将您的选择器更改为:
$(".deleteEvent").click(function(e) {
// code
});
或者,您可能会完全删除id
或class
因为您仍然可以标识没有id
或class
的元素:
$("#students a").click(function(e) {
// code
});
用这个
<script type="text/javascript">
$(function() {
$("#deleteEvent").click(function(e) {
$(this).parent('tr').remove();
});
</script>
请用以下给出的函数替换您的函数。 它的工作。 我已经检查过了
$(function() {
$("table a").click(function(e) {
$(this).parent().parent().remove();
return false;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.