javascript - 在表单中使用 jQuery 使用箭头键跳转到下一个输入字段

标签 javascript jquery html

我想使用箭头键在我的表单(下一个、上一个)中的输入文本字段之间导航。我找到了这个简单的方法来实现它:link to it但对我来说它不起作用......我也在 FORM 之后的 HEAD 和 BODY 中尝试了它,但没有运气......

我认为问题可能是我的表单通过 AJAX 发送回页面...

我对 jQuery 不是很熟悉,有人可以帮我吗?

这是 jQuery 代码:

<script>
$(document).ready(function(){
$('input').keyup(function(e){
if(e.which==39)
$(this).closest('td').next().find('input').focus();
else if(e.which==37)
$(this).closest('td').prev().find('input').focus();
else if(e.which==40)
$(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input').focus();
else if(e.which==38)
$(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input').focus();
});
});
</script>

最佳答案

如果您的输入是在 domready 事件之后动态创建的,您应该更改

$('input').keyup(function(e){
   ...

进入

$('body').on('keyup', 'input', function(e) {
   ...

这样做,keyup 事件将使用事件委托(delegate)在 body 元素上捕获

有关更多信息,请参阅此处的文档:http://api.jquery.com/on/

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler...

关于javascript - 在表单中使用 jQuery 使用箭头键跳转到下一个输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13248319/

相关文章:

javascript - 首先为厨房加载 "Loading"图像

javascript - 在另一个 Canvas 中添加 Canvas : obj. setCoords 不是函数(fabric js)

javascript - 将浏览器位置聚焦在切换 block 上

javascript - 连续删除先到元素

javascript - 禁止文件夹 1 从文件夹 2 导入任何内容

javascript - 如何获取 JSON URL 文件并使其不断更新

javascript - 鼠标悬停时同时在 2 个 div 上发生事件

javascript - 排除特定单词及其后面的任何内容

javascript - 平滑滚动效果在 Mozilla 和 IE 中不起作用?

html - angular 2 包括 html 模板