Javascript 使用JS或Jquery在整个HTML表中插入包含按钮的行
我正在尝试构建一个应用程序,帮助人们按照特定的顺序列出他们的开支。如何允许他们在特定点添加行 从一个简单的HTML表开始,如下所示:Javascript 使用JS或Jquery在整个HTML表中插入包含按钮的行,javascript,jquery,html-table,rows,Javascript,Jquery,Html Table,Rows,我正在尝试构建一个应用程序,帮助人们按照特定的顺序列出他们的开支。如何允许他们在特定点添加行 从一个简单的HTML表开始,如下所示: <table id='exptable'> <tr> <td>(date)</td> <td><input type='text' placeholder='Expense type (rent, groceries, etc.)'/></td> <td>&
<table id='exptable'>
<tr>
<td>(date)</td>
<td><input type='text' placeholder='Expense type (rent, groceries, etc.)'/></td>
<td><input type='number' value='.00'/></td>
<td><input type='button' class='addrow' value='Add Row Below'/></td>
<td><input type='button' class='delrow' value='Delete' /></td>
</tr>
<tr>
<td>(date)</td>
<td><input type='text' placeholder='Expense type (rent, groceries, etc.)'/></td>
<td><input type='number' value='.00'/></td>
<td><input type='button' class='addrow' value='Add Row Below'/></td>
<td><input type='button' class='delrow' value='Delete' /></td>
</tr>
</table>
$('#exptable').on('click', '.delrow', function(){
$(this).parent().parent().remove();
});
至于insert按钮,它们最终将能够对行重新排序,因此为每一行分配一个唯一的ID似乎是不可行的。以下是我现在掌握的残暴代码:
$('.addrow').click(function(){
$("<tr><td></td><td><input type='text' placeholder='Inserted Row'/></td><td><input type='number' value='.00' class='dollar ' size='8'/></td><td><input type='button' class='addrow' value='Add Row Below'/></td><td><input type='button' class='delrow' value='Delete' /></td></tr>").insertAfter(this.parentNode.parentNode);
});
$('.addrow')。单击(函数(){
$(“”).insertAfter(this.parentNode.parentNode);
});
这会在需要的位置插入行。但是,新行中的两个按钮都不起作用。为什么不起作用?有没有一种更聪明的方法可以在任何地方插入行
问题在于绑定单击的代码:
$('.delrow').click(function(){
$(this).parent().parent().remove();
});
仅适用于调用DOM时DOM中存在的与.delrow
匹配的元素。它不适用于以后添加的任何匹配元素
相反,请使用一个将侦听器放在共享父级上并委托给目标选择器的方法。大概是这样的:
<table id='exptable'>
<tr>
<td>(date)</td>
<td><input type='text' placeholder='Expense type (rent, groceries, etc.)'/></td>
<td><input type='number' value='.00'/></td>
<td><input type='button' class='addrow' value='Add Row Below'/></td>
<td><input type='button' class='delrow' value='Delete' /></td>
</tr>
<tr>
<td>(date)</td>
<td><input type='text' placeholder='Expense type (rent, groceries, etc.)'/></td>
<td><input type='number' value='.00'/></td>
<td><input type='button' class='addrow' value='Add Row Below'/></td>
<td><input type='button' class='delrow' value='Delete' /></td>
</tr>
</table>
$('#exptable').on('click', '.delrow', function(){
$(this).parent().parent().remove();
});
…应该足以满足您的需要。另外,我建议抛弃链式的
.parent().parent()
,用不太脆弱的东西替换它,比如:$(this.nexist('tr').remove()代码>在这里学习新事物的可能重复。回答得好!