1 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
您不能在 HTML 中復(fù)制 ID。您可以將行號(hào)保存在每次添加新行時(shí)遞增的變量中,并使用該變量生成 ID:
$(function() {
let row = 1;
$('#addRow').click(function() {
row++;
let temp_td = '<tr><th scope="row">' + row + '</th><td><label><input type="text" name="name"></label></td><td><label><input type="text" id="price' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="qt' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="ttl' + row + '" name="total"></td><td><button class="remove">-</button></td></tr>';
$('tbody').append(temp_td)
});
$(document).on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
function calculate(r) {
var price = document.getElementById('price' + r).value;
var qt = document.getElementById('qt' + r).value;
var ttl = document.getElementById('ttl' + r);
var multiply = price * qt;
ttl.value = multiply;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="table-responsive container">
<table class="table">
<thead class="dark">
<tr>
<th scope="col">SL.</th>
<th scope="col">Item Description</th>
<th scope="col">Price</th>
<th scope="col">Qty.</th>
<th scope="col">Total</th>
<th scope="col">Del</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><label>
<input type="text" name="name">
</label>
</td>
<td><label>
<input type="text" id="price1" oninput="calculate(1)">
</td>
<td>
<input type="text" id="qt1" oninput="calculate(1)">
</td>
<td>
<input type="text" id="ttl1" name='total'>
</td>
<td>
<button class="remove">-</button>
</td>
</tr>
</tbody>
</table>
<button id="addRow">+ Add</button>
如果您愿意,您也可以對(duì)名稱執(zhí)行此操作。我在上面的代碼中沒有這樣做,因?yàn)樗鼘?duì)于這個(gè)答案不是必需的。
或者,您可以將元素本身傳遞給calculate()函數(shù),然后使用 jQuery 查找其他“兄弟”元素。所以你根本不需要身份證。
添加回答
舉報(bào)