如何使用 jQuery 自动切换到下一个字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6360594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I automatically tab to the next field using jQuery?
提问by Nathan Long
In jQuery, how can I trigger the behavior of a user tabbing to the next input field?
在 jQuery 中,如何触发用户跳转到下一个输入字段的行为?
I've tried this:
我试过这个:
var e = jQuery.Event("keydown");
e.which = 9; // # Key code for the Tab key
$("input").trigger(e);
But triggering the event doesn't move the cursor to the next field.
但是触发事件不会将光标移动到下一个字段。
I suppose I could move the cursor manually using focus()
, but deciding which field should be next is something the browser already knows how to do, so it seems much cleaner to just trigger a tab.
我想我可以使用 手动移动光标focus()
,但决定下一个应该是哪个字段是浏览器已经知道如何做的事情,所以只触发一个选项卡似乎更清晰。
Any ideas?
有任何想法吗?
采纳答案by James Allardice
See the accepted answer to this question. If for example you want to move focus to the next field when a certain number of characters have been entered, you could use that code in the keyup
event, and check the entered number of characters.
请参阅此问题的已接受答案。例如,如果您想在输入一定数量的字符后将焦点移到下一个字段,您可以在keyup
事件中使用该代码,并检查输入的字符数。
The code in that answer works by getting the set of inputs in the form, finding the selected input and adding 1 to the index of the selected input, and then triggering the focus
event on the element with that index.
该答案中的代码通过获取表单中的一组输入、找到所选输入并将 1 添加到所选输入的索引,然后focus
在具有该索引的元素上触发事件来工作。
回答by Yardboy
Here's one solution, via http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/
这是一种解决方案,通过http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/
$.fn.focusNextInputField = function() {
return this.each(function() {
var fields = $(this).parents('form:eq(0),body').find(':input').not('[type=hidden]');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false;
});
};
The use is as follows:
使用方法如下:
$( 'current_field_selector' ).focusNextInputField();
回答by laffuste
回答by JimP
Have you tried using
你有没有试过使用
$("input").trigger( 'keypress', e );
$("input").trigger( 'keypress', e );
as a solution?
I find sometimes being explicit is best.
If that doesn't work possibly even
作为解决方案?
我发现有时明确是最好的。如果那甚至行不通
$("input").trigger( 'keypress', [{preventDefault:function(){},keyCode:9}] );
.
$("input").trigger( 'keypress', [{preventDefault:function(){},keyCode:9}] );
.
Hope this helps.
希望这可以帮助。