我正在创建带有表格的表格,该表格将与条形码扫描仪一起使用。表格行将从第一行开始,每次使用扫描仪时,首先将创建新行,然后将焦点移至新创建行的特定输入。 (基本上跳过开始行上存在的其他输入)。
我找到了一个类似的主题,并且到现在为止,但是我既不能创建新行又不能移动到新行以在另一行之外协同工作。我可以使用委派,但这会中断将焦点移到下一行的输入...
<table id="table1">
<tr>
<td><input class="bcode" type="text" name="S1" autofocus/></td>
<td><input class="b" type="text" name="S2" /></td>
<td><input class="c" type="text" name="S3" /></td>
</tr>
</table>
$('#table1').find('.bcode').keypress(function(e){
if ( e.which == 13 ){
$('<tr><td><input class="bcode" type="text" name="S1" /></td><td><input class="b" type="text" name="S2" /></td><td><input class="c" type="text" name="S3"/></td></tr>').appendTo('#table1');
$(this).parent().parent().next('tr').find('.bcode').focus();
return false;
}
});
答案 0 :(得分:0)
对于附加到动态DOM元素的事件,应使用.on()。然后:
$(document).on("keyup", ".bcode",(function(e){
//code
}));
收听新创建的.bcode
元素。
您可以通过以下方式限制哪些.bcode
元素:
$("#table1").on("keyup", ".bcode",(function(e){
//code
}));
答案 1 :(得分:0)
您可以在此处使用.on()
将事件附加到现有表并将其委托给输入的按键。
$('#table1').on('keypress', '.bcode', function(e) {
if ( e.which == 13 ) // Enter key = keycode 13
{
$('<tr><td><input class="bcode" type="text" name="S1" /></td><td><input class="b" type="text" name="S2" /></td><td><input class="c" type="text" name="S3" /></td></tr>').appendTo('#table1');
//console.log($(this).next('.bcode'));
$(this).parent().parent().next('tr').find('.bcode').focus();
return false;
}
});
请参阅随附的小提琴。 https://jsfiddle.net/pmewsqLn/