【发布时间】:2023-12-02 08:58:01
【问题描述】:
我有下表
<table id="invoice">
<tr>
<th>Quantity</th>
<th>Item</th>
<th><input type="button" id="addnew" name="addnew" value="Add Row" />
</th>
</tr>
<tr id="id1">
<td><input id="quantity1" name="quantity[]" tabindex="1" type="text" value="" /></td>
<td><select id="rate1" name="rate[]" tabindex="2" value="">
<option value="">SELECT</option>
<option value="1">ONE</option>
<option value="2">TWO</option>
</select></td>
<td><input id="remove1" name="remove[]" tabindex="3" type="button" value="Remove Row"class="remove"/></td>
</tr>
</table>
我可以使用以下脚本添加行
var next = 2;
function addrow(table,add)
{
$(add).bind('click', function() {
var $last = $(table + ' tr:last');
var last_row = $last.clone();
$(last_row).find(":input").each(function() {
var store = $(this).attr("id");
var new1 = store.replace(/1/, next);
$(this).attr("id",new1);
});
last_row.appendTo($(table))
$(table+" tr:last").hide().fadeIn('slow');
next++;
});
}
addrow('#invoice','#addnew');
上面的脚本克隆第二行并附加到实际需要的表中。但问题是,如果用户在文本框的第二行输入一些值,然后单击 addrow,它会在新行中复制这些值。为了克服这个问题,我只需更改脚本。
所以我将脚本更改为以下内容
var next = 2;
function addrow(table,add)
{
var $last = $(table + ' tr:last');///changed this line
var last_row = $last.clone(); /// changed this line
$(add).bind('click', function() {
$(last_row).find(":input").each(function() {
var store = $(this).attr("id");
var new1 = store.replace(/1/, next);
$(this).attr("id",new1);
});
last_row.appendTo($(table))
$(table+" tr:last").hide().fadeIn('slow');
next++;
});
}
这只会添加一行,它只是更改最后一行,但不会添加超过新行。
任何人都可以更正第二个脚本,因为它非常适合我的项目,因为许多其他脚本都与此相关联。
【问题讨论】: