使用回车键按下表格中的下一个输入字段
我需要使用回车键按下移动到具有多行的表中的下一个输入字段。 我试试这个:
$(function() { $('input').keyup(function (e) { if (e.which == 13) { $(this).find().next('input').focus(); } }); });
为什么不工作? 🙁
HTML
Nome : Mnemo: Partita IVA : Nome : Mnemo: Partita IVA :
此代码工作正常,但只在表的第一行:
$('input').keydown(function (e) { if (e.which === 13) { $(this).closest('td').nextAll().eq(1).find('input').focus() } });
有什么不对或缺失?
假设.inputs
是您当前元素的兄弟。 .find()
搜索当前元素的后代(this)
$('.inputs').keydown(function (e) { if (e.which === 13) { $(this).next('.inputs').focus(); } });
你需要使用.closest() ,. nextAll()
$('.inputs').keydown(function (e) { if (e.which === 13) { $(this).closest('td').nextAll().eq(1).find('.inputs').focus(); //OR //$(this).closest('td').next().next().find('.inputs').focus() } });
DEMO
由于OP已更新问题。 使用
$('.inputs').keydown(function (e) { if (e.which === 13) { var index = $('.inputs').index(this) + 1; $('.inputs').eq(index).focus(); } });
演示 ,注意我使用了class="inputs"
也许它不起作用,因为你没有使用find()
方法的任何参数。
并试试这个:
$('#txt').keydown(function (e){ if(e.keyCode == 13){ $(this).next('.inputs').focus(); } });
或这个:
$('#txt').keydown(function (e){ if(e.keyCode == 13){ $(this).find('.inputs').focus(); } });
这些会奏效!
$('.inputs').keydown(function (e){ if(e.keyCode == 13){ $(this).next('.inputs').focus(); } });
它是:
if (event.which == 13) { event.preventDefault(); var $this = $(event.target); var index = parseFloat($this.attr('data-index')); $('[data-index="' + (index + 1).toString() + '"]').focus(); }
字体:
专注于下一个输入(jquery)