如何在 HTML 表单中聚焦新创建的字段?

How to focus a newly created field in a HTML form?

我想在用户单击 link 时将输入字段动态添加到 html 表单。新创建的字段应获得键盘焦点。

How to Set Focus on Input Field using JQuery 的答案对我不起作用(Whosebug 上的任何其他答案也不适用)。新创建的字段没有获得键盘焦点。在 Firefox 43.0.1 和 Chromium 18 中测试。当我键入(如 CTRL+F)时,Firefox 开始查找文本,Chromium 什么都不做。我尝试了来自本地文件和网络服务器的代码,其中包含 jQuery.

的各种版本
function addfield() {
  n = $('table#t1 tr').length;
  $('table#t1').append('<tr><td><input name=field'+n+' ></td><td><input name=value'+n+'></td></tr>');
  $('input[name="field"'+n+']').focus();
}
a { background: tan; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table id=t1>
  <thead>
    <tr>
      <th>field</th>
      <th>value</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Bill</td>
      <td>bill@yahoo.com</td>
    </tr>
  </tbody>
</table>
<div><a onclick='addfield();return false;'>Add field</a></div>

您似乎对 jQuery 选择器中的名称 属性 有疑问,该名称应该聚焦新添加的字段。选择器的 " 部分放错了。

您当前的密码是

$('input[name="field"'+n+']').focus();

应该是:

$('input[name="field'+n+'"]').focus();

您可以查看此 JSFiddle an example