使用多个输入框按“输入" [英] Pressing 'enter' with multiple input boxes

查看:78
本文介绍了使用多个输入框按“输入"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML表单,其中包含几个输入框和它们相应的输入按钮.当我在第一个输入框中键入内容并按 Enter 或按钮时,它可以正常工作.但是,如果我在其他框中按 Enter ,则它就像在第一个框中一样.按钮工作正常.

I have an HTML form with several input boxes and their corresponding enter button. When I type something in the first input box and either press Enter or the button, it works fine. But if I press Enter in the other boxes it works as if it was in the first box. The buttons work OK.

这是我的代码:

<script type="text/javascript">
  function fn (num) {
    alert(num);
    document.getElementById(num).focus();
  }
</script>
</head>
<body>
<form>
  <input id="1" type="text"></input> <button onclick="fn(1);">press</button><br/>
  <input id="2" type="text"></input> <button onclick="fn(2);">press</button><br/>
  <input id="3" type="text"></input> <button onclick="fn(3);">press</button><br/>
</form>

显然,这是ECMA中的一个怪胎"(我已经在FF18.0.1和Safari 5.1.7中进行了测试). 这个怪癖有解决方法吗?

Apparently this is a 'quirk' in ECMA (I have tested in FF18.0.1 and Safari 5.1.7). Is there a fix for this quirk?

我发现的一种解决方案是在每个输入框中添加一个表单.

One solution that I found is to add one form per input box.

<form>
  <input id="1" type="text"></input> <button onclick="fn(1);">press</button><br/>
</form>
<form>
  <input id="2" type="text"></input> <button onclick="fn(2);">press</button><br/>
</form>
<form>
  <input id="3" type="text"></input> <button onclick="fn(3);">press</button><br/>
</form>

这是错误还是功能?有更好的解决方案吗? 感谢您的任何建议.

Is this a bug or a feature? Is there a better solution? Thanks for any suggestions.

推荐答案

您将要使用onKeyPress而不是onClick.试试这个:

You'll want to use onKeyPress instead of onClick. Try this:

function myKeyPress(args) {
  if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    // do something here (enter has been pressed)
  }
  else {
    return false; // somehow prevents "default" form behaviors
  }
}

这篇关于使用多个输入框按“输入"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆