[英]Setting Unique ID's of form elements on dynamic creation
我正在制作腳本以動態添加行。 我正在使用以下功能。 但是,問題在於它確實創建了新行,但沒有為元素分配唯一的ID。
Javascript:
$(document).ready(function () {
var counter = 1;
$("#add_row").click(function () {
var row_id = "row" + counter;
console.log(row_id);
new_elem = $("#new_row").clone().appendTo("#table_invoice tbody").show().attr("id", row_id);
var button_id = "button" + row_id;
var input_id = "row" + row_id;
document.getElementById('row_id').firstChild.setAttribute('id',input_id);
document.getElementById('row_id').firstChild.nextSibling.setAttribute('id',button_id);
console.log(button_id);
console.log(input_id);
counter += 1;
});
});
HTML:
<table class="table table-striped" id="table_invoice">
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
<tr id ="new_row" style="display:none;">
<th><input type="text" class="form-control" placeholder="Enter Product ID" /></th>
<th><button type="button" class="btn btn-default"">Add Product</button></th>
<th></th>
<th></th>
</tr>
</tbody>
</table>
<a id="add_row" class="btn bt-default">Add New Row</a>
另外,我得到以下錯誤:
TypeError:document.getElementById(...)。firstChild.setAttribute不是函數
無法弄清楚為什么這不是有效函數。
這意味着無法在上述方法中找到元素,直到firstChild
。 由於找不到元素,因此鏈上的值在該點是不確定的,當然,它沒有方法setAttribute
。 如果找到了您要查找的元素,則不會發生該錯誤。
The problem is you're doing this:
document.getElementById('row_id')
當你的意思
document.getElementById('row_id')
...即row_id
是一個變量,應這樣指定,而不是字符串。
使用jQuery,這是您的工作方式: 演示
請注意,我已將所有row_id
更改為計數器,因為我認為這是預期的方法。
$(document).ready(function () {
var counter = 1;
$("#add_row").click(function () {
var row_id = "row" + counter;
console.log(row_id);
new_elem = $("#new_row").clone().appendTo("#table_invoice tbody").show().attr("id", row_id);
var button_id = "button" + counter;
var input_id = "input" + counter; //I think you meant "input" because if you set "row" at the beginning it would be duplicated of the tr
$('#'+row_id).find('button').attr('id',button_id);
$('#'+row_id).find('input').attr('id',input_id);
console.log(button_id);
console.log(input_id);
counter++;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.