【问题标题】:How to focus a newly created field in a HTML form?如何在 HTML 表单中聚焦新创建的字段?
【发布时间】:2016-08-21 08:15:05
【问题描述】:

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

How to Set Focus on Input Field using JQuery 的答案对我不起作用(StackOverflow 上的任何其他人也一样)。新创建的字段不接收键盘焦点。在 Firefox 43.0.1 和 Chromium 18 中测试。当我键入时 Firefox 开始查找文本(如 CTRL+F),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 html focus input-field


    【解决方案1】:

    您的 jQuery 选择器中的 name 属性似乎有问题,它应该关注新添加的字段。选择器的" 部分放错了位置。

    你当前的代码是

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

    应该是:

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

    您可以查看此 JSFiddle 以获取 an example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      相关资源
      最近更新 更多