我创建了一个动态数据输入表。并且我已经添加了自动完成功能,它工作正常。但问题是如果我在动态表中添加了新行,则自动完成功能无法在该行上运行。如何解决这个问题?
******** ******** HTML
<table class="table table-bordered" id="curd_table">
<tr>
<th width="15%">User ID</th>
<th width="20%">Name</th>
<th width="20%">NIC</th>
<th width="20%">Amount</th>
<th width="25%">Pay date (YYYY-MM-DD)</th>
<th></th>
</tr>
<tr>
<td contenteditable="true" class="uid " name="uid" id="uidr"></td>
<td contenteditable="true" class="name " name="name" id="namer"></td>
<td contenteditable="true" class="nic" name="nic" id="nicr"></td>
<td contenteditable="true" class="amount"></td>
<td contenteditable="true" class="paydate"></td>
<td></td>
</tr>
</table>
**** JS功能****
$(document).ready(function(){
var count=1;
$('#add').click(function(){
count=count+1;
var html_code ="<tr id='row"+count+"'>";
html_code +="<td contenteditable='true' class='uid' name='uid' id='uidr'></td>";
html_code +="<td contenteditable='true' class='name' name='name' id='namer'></td>";
html_code +="<td contenteditable='true' class='nic' name='nic' id='nicr'></td>";
html_code +="<td contenteditable='true' class='amount'></td>";
html_code +="<td contenteditable='true' class='paydate'></td>";
html_code +="<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code +="</tr>";
$('#curd_table').append(html_code);
});
$('#uidr').autocomplete({
source: function( request, response ) {
$.ajax({
url : '../control/autoComp.php',
dataType: "json",
method: 'POST',
data: {
id_startsWith: request.term,
type: 'pay_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui ) {
var names = ui.item.data.split("|");
$('#namer').text(names[1]);
$('#nicr').text(names[2]);
}
});
});
自动完成无法使用红色箭头标记。这些是动态添加的行。
答案 0 :(得分:0)
您应该更改jquery选择器以选择类,而不是id(唯一值)。
你错过了&#39;})&#39;关闭&#39; $(文件).ready(function(){&#39;
修改强> 如果动态添加组件,则应使用on()函数将事件绑定到新添加的组件。
$(document).on('autocomplete','.uid',function(){
source: function( request, response ) {
$.ajax({
url : '../control/autoComp.php',
dataType: "json",
method: 'POST',
data: {
id_startsWith: request.term,
type: 'pay_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui ) {
var names = ui.item.data.split("|");
$(this).nextAll('.name').text(names[1]);//or just next()
$(this).nextAll('.nic').text(names[2]);//or just next().next()
}
});