首页 > 解决方案 > 使用 jQuery 动态添加/删除行

问题描述

我正在使用 jQuery 动态添加/删除行。

jQuery代码如下:

$(document).ready(function() {
    var i = 1;
    $('#add_row').click(function() {
        $('#addr' + i).html("<td>&nbsp;" + (i + 1) + "&nbsp;</td><td><input class='tbl_text' maxlength='250' name='invoiceNo[]' size='25' style='text-transform:uppercase' type='search' required /></td><td><input class='date' max='2099-12-31' name='date[]' onkeydown='return false' type='date' required /></td><td><input class='tbl_text' maxlength='500' name='desc[]' size='50' type='search' required /></td><td><input class='amt' name='amt[]' step='0.01' type='number' required /></td>");
        $('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
        i++;
    });

    $('#delete_row').click(function() {
        if (i > 0) {
            $('#addr' + i).remove();
            calculateSum();
            i--;
        }
    });
});

HTML如下:

    <table align="center" border="1" class="table table-bordered table-hover" id="tab_logic" style="border:2px solid black;border-collapse:collapse">
<thead>
<tr>
<th width="25" />&nbsp;
<th>Invoice No.</th>
<th>Invoice Date</th>
<th>Description</th>
<th>Amount S$<br>(Including GST)</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>&nbsp;1&nbsp;</td>
<td align="center"><input class="tbl_text" maxlength="250" name="invoiceNo[]" size="25" style="text-transform:uppercase" type="search" required /></td>
<td align="center"><input class="date" max="2099-12-31" name="date[]" onkeydown="return false" type="date" required /></td>
<td align="center"><input class="tbl_text" maxlength="500" name="desc[]" size="50" type="search" required /></td>
<td align="center"><input class="amt" id="amt" name="amt[]" step="0.01" type="number" required /></td>
</tr>
<tr id='addr1'></tr>
</tbody>
<tr>
<td colspan="5" height="5" style="border:none;" />
</tr>
<tr>
<td align="right" colspan="5" height="50" style="border:none;"><button class="button" id="add_row" type="button">Add Row</button><span style='display:inline-block;width:1em;'>&nbsp;</span><button class="button_cancel" id="delete_row" type="button">Delete Row</button><span style='display:inline-block;width:0.5em;'>&nbsp;</span></td>
</tr>
<tr>
<td colspan="5" height="5" style="border:none;" />
</tr>
<tr height="50" id="summation">
<td class="label" colspan="4">&nbsp;Total Amount Payable</td>
<td align="right" class="label"><span id="sum">$0.00</span></td>
</tr>
</table>

它正在工作,但有时,我需要在执行该功能之前单击按钮两次,有时我只需要单击一次。

我错过了什么吗?请有什么建议,谢谢。

标签: jquery

解决方案


推荐阅读