我试图在一定数量的字符后自动跳转到第二行。我在jquery中使用keypress函数来执行此操作。这是我的代码:
<html>
<head>
<script type="text/javascript" src="http://inet.website-name.com/jquery/jquery-1.7.min.js"></script>
</head>
<body>
<input id="input1"></input>
<br />
<input id="input2"></input>
<script type="text/javascript">
$('#input1').keypress(function (e) {
var tval = $('#input1').val();
if (tval.length >= 5 && e.which !== 0 && e.charCode !== 0) {
$('#input2').focus();
}
})
</script>
</body>
</html>
我遇到的问题是当它在chrome中运行时,在第一个框中键入第6个字符,然后将焦点更改为第二个框。在Internet Explorer中运行此操作时,焦点首先更改为第二个框,然后键入第6个字符。我需要它在两个浏览器中都有相同的行为。
我尝试使用keydown事件并且在改变焦点方面起作用,但即使我使用退格键,箭头键或任何其他特殊键,焦点也会改变。
提前谢谢。
答案 0 :(得分:0)
您可以将其切换为keyup事件并且它将起作用,但您将无法使用e.charCode检查(是否有原因?)。另请注意,&gt; = 5 已更改为&gt; 5 强>
$('#input1').keyup(function (e) {
var c = String.fromCharCode(e.keyCode);
var isWordcharacter = c.match(/\w/);//matches a-z, A-Z, 0-9, and _
var tval = $('#input1').val();
if (tval.length > 5 && e.which !== 0 && isWordcharacter) {
$('#input2').focus();
}
});