首页 > 解决方案 > 使用 JS/jQuery 将 tabindex 附加到输入标签

问题描述

我正在尝试为输入字段设置 tabindex,但我无权访问 HTML。

我们正在插入一个由第三方生成的表单。此表单按顺序有两个字段,邮政编码和电子邮件地址。我想使用 CSS 重新排列它们(无需修改源平台上的字段),因此电子邮件高于邮政编码,但显然这会扰乱标签顺序。

输入分别具有 PostalCode 和 EmailAddress 的名称属性。我对 JS 知之甚少,所以我试图从 Internet 上的资源中拼凑起来,到目前为止没有成功。

我尝试了以下方法,但它不起作用,我显然无法弄清楚为什么或如何正确地做到这一点。

document.getElementsByName("EmailAddress")[0].setAttribute("tabIndex", "1");
document.getElementsByName("PostalCode")[0].setAttribute("tabIndex", "2");
document.getElementsByClass("at-submit")[0].setAttribute("tabIndex", "3");

标签: javascriptjqueryhtmlforms

解决方案


这行得通。

请注意,我只是增加元素以获得更高的索引。

const displayTabIndex = (name, { tabIndex }) => console.log(`${name} - ${tabIndex}`);

document.addEventListener('DOMContentLoaded', () => {
  const tel = document.querySelector('input[type="tel"');
  const pCode = document.querySelector('input[name="PostalCode"]');
  displayTabIndex('tel', tel);
  displayTabIndex('pCode', pCode);

  pCode.setAttribute('tabIndex', 3);
  
  displayTabIndex('tel', tel);
  displayTabIndex('pCode', pCode); 
});
<form>
  <input type="tel" name="tel" tabindex="2">
  <input type="text" name="PostalCode" tabindex="1">
</form>


推荐阅读