Simulate pressing tab key with jQuery
我在.net页上有一些文本框,并希望通过jQuery实现以下功能:如果用户按return键,则程序应表现为"好像"他使用了tab键,因此选择了下一个元素。 我尝试了以下代码(还有更多):
1 2 3 4 5 6 7 8 9 10 11 12 | <script type="text/javascript"> jQuery(document).ready(function () { $('.tb').keypress(function (e) { if (e.keyCode == 13) { $(this).trigger("keydown", [9]); alert("return pressed"); } }); }); |
1 2 | </asp:TextBox> </asp:TextBox> |
但这是行不通的! 缺少东西,犯错了吗?
这是我使用的一些链接
这里
和这里
试试这个:
http://jsbin.com/ofexat
1 2 3 4 5 | $('.tg').bind('keypress', function(event) { if(event.which === 13) { $(this).next().focus(); } }); |
或循环版本:http://jsbin.com/ofexat/2
我创建了一个简单的jQuery插件来解决此问题。 它使用jQuery UI的':tabbable'选择器来查找下一个'tabbable'元素并将其选中。
用法示例:
1 2 3 4 5 6 7 8 9 10 11 12 | // Simulate tab key when enter is pressed $('.tb').bind('keypress', function(event){ if(event.which === 13){ if(event.shiftKey){ $.tabPrev(); } else{ $.tabNext(); } return false; } }); |
从多个答案中,我为自己组合了一个完美的解决方案,其中enter充当输入的选项卡,然后选择并关注下一个输入,select或textarea,同时允许在文本区域内输入。
1 2 3 4 5 6 7 8 | $("input,select").bind("keydown", function (e) { var keyCode = e.keyCode || e.which; if(keyCode === 13) { e.preventDefault(); $('input, select, textarea') [$('input,select,textarea').index(this)+1].focus(); } }); |
试试这个
1 2 3 4 | $(this).trigger({ type: 'keypress', which: 9 }); |