[英]How do we get the particular dynamically added td's id in jquery on function
[英]how to get a particular cell from a dynamically added row based on its id in jQuery
我有一個帶有id line-creation-table
,該line-creation-table
可以動態增長或收縮。 該表中的每一行如下所示:
<tr>
<td><input type="text" name="brand" /></td>
<td><input type="text" name="itemRefNo" id="itemRefNo"/></td>
<td> <input type="number" name="quantity" value="1"/></td>
<td> <input type="text" name="unitPrice" /></td>
<td><input type="date" name="deliveryDate" /></td>
<td><input type="button" value="Show Previous Actions" id="showPreviousActions"/></td>
</tr>
這些行是動態添加的。 現在,當單擊showPreviousActions
按鈕時,我想從單擊按鈕的行中的itemRefNo
單元中檢索值。
我嘗試了這個:
$("#line-creation-table").on('click', 'input[id="showPreviousActions"]', function(event) {
var itemRefNo = $(this).parent().find('input[id="itemRefNo"]').val();
}
和這個:
var itemRefNo = $(event.target).closest('input[id="itemRefNo"]').val();
但都沒有奏效。 當我在控制台日志中登錄itemRefNo
變量時,我將undefined
。 我該如何解決? 非常感謝你。
這段代碼:
$(this).parent()
接受當前項(此=按鈕)並獲取其父項(即按鈕的td
,因此嘗試在相鄰單元格中查找輸入失敗。
一個快速的解決方法是讓td
的父級tr
給出:
$("#line-creation-table").on('click', 'input[id="showPreviousActions"]', function(event) {
var itemRefNo = $(this).parent().parent()
.find('input[id="itemRefNo"]').val();
}
更好的方法是使用closest()
查找按鈕的行:
$("#line-creation-table").on('click', 'input[id="showPreviousActions"]', function(event) {
var row = $(this).closest("tr");
var itemRefNo = row.find('input[id="itemRefNo"]').val();
}
其中closest()
與遞歸調用.parent()
相同,直到找到匹配的節點(即最接近的父節點.parent()
為止。
您可以使用
$('#showPreviousActions').click(function () {
var aa = $(this).closest('tr').find('#itemRefNo').val();
});
好吧,我這邊是一個非常愚蠢的錯誤。 為該表動態創建一行時,我忘記在那里更改代碼,因此在新創建的行中將有一個id為itemRefNo
的輸入。 舊代碼:
$('#line-creation-table').append("<tr>" +
"<td><input type='text' name='brand' /></td>" +
"<td><input type='text' name='itemRefNo' /></td>" +
"<td> <input type='number' name='quantity' value='1'/></td>" +
"<td> <input type='text' name='unitPrice' /></td>" +
"<td><input type='date' name='deliveryDate' /></td>" +
"<td><input type='button' value='Show Previous Actions' id='showPreviousActions'/></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
新代碼:
$('#line-creation-table').append("<tr>" +
"<td><input type='text' name='brand' /></td>" +
"<td><input type='text' name='itemRefNo' id='itemRefNo'/></td>" +
"<td> <input type='number' name='quantity' value='1'/></td>" +
"<td> <input type='text' name='unitPrice' /></td>" +
"<td><input type='date' name='deliveryDate' /></td>" +
"<td><input type='button' value='Show Previous Actions' id='showPreviousActions'/></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
因此,@freedomn -m的建議都起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.