利用jQuery实现商表格的添加
以下是利用jQuery实现商表格的添加的示例代码:
HTML代码:
<table id="myTable">
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>金额</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="price"></td>
<td><input type="text" name="quantity"></td>
<td><input type="text" name="amount" readonly></td>
<td><button type="button" class="btn-add">添加</button></td>
</tr>
</tbody>
</table>
JavaScript代码:
$(document).ready(function() {
// 计算金额
function calculateAmount(row) {
var price = row.find('input[name="price"]').val();
var quantity = row.find('input[name="quantity"]').val();
var amount = price * quantity;
row.find('input[name="amount"]').val(amount.toFixed(2));
}
// 添加行
$('.btn-add').click(function() {
var row = $(this).closest('tr').clone();
row.find('input').val('');
row.find('input[name="amount"]').removeAttr('readonly');
row.find('.btn-add').removeClass('btn-add').addClass('btn-remove').text('删除');
$('#myTable tbody').append(row);
});
// 删除行
$(document).on('click', '.btn-remove', function() {
$(this).closest('tr').remove();
});
// 计算金额
$(document).on('input', 'input[name="price"], input[name="quantity"]', function() {
var row = $(this).closest('tr');
calculateAmount(row);
});
});
说明:
- 在HTML代码中,我们创建了一个表格,并设置了一个带有文本框和“添加”按钮的行。
- 在JavaScript代码中,我们定义了一个用于计算金额的函数,并在添加行和输入单价或数量时调用此函数。
- 我们通过单击“添加”按钮来添加新行,并通过单击“删除”按钮来删除行。
- 我们使用了jQuery的事件委托功能,以便在添加新行后仍然能够计算金额。
- 最后,我们将所有代码包装在$(document).ready()函数中,以确保在DOM加载完成后运行。
原文地址: https://www.cveoy.top/t/topic/beki 著作权归作者所有。请勿转载和采集!