You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同名表单字段获焦时获取其索引编号?

如何判断同名input组中获焦字段的索引?

很简单,你只需要利用传入的this(也就是当前获焦的input元素),结合表单里的字段集合来找到它的索引就行。这里给你两种可行的方法:

方法一:转数组后用indexOf(简洁现代)

直接把表单的字段集合转成数组,然后用indexOf方法快速定位当前元素的索引,代码如下:

<form name="formName">
  <input type=text name=fieldName onFocus="see(this)">
  <input type=text name=fieldName onFocus="see(this)">
  <input type=text name=fieldName onFocus="see(this)">
</form>
<script>
document.formName.fieldName[2].value = "two"; // 设置第三个字段的值(索引从0开始)

function see(that) {
  // 获取表单中所有name为fieldName的input集合
  const allFields = document.formName.fieldName;
  // 把类数组的HTMLCollection转成真正的数组
  const fieldsArray = Array.from(allFields);
  // 找到当前元素在数组中的索引
  const fieldIndex = fieldsArray.indexOf(that);
  
  console.log(`当前获焦的是索引为 ${fieldIndex} 的字段`);
  // 你也可以在这里做其他操作,比如修改对应字段的样式或者内容
}
</script>

方法二:循环遍历(兼容老浏览器)

如果需要兼容IE这类不支持Array.from的老浏览器,用循环逐个对比元素也是个可靠的办法:

<form name="formName">
  <input type=text name=fieldName onFocus="see(this)">
  <input type=text name=fieldName onFocus="see(this)">
  <input type=text name=fieldName onFocus="see(this)">
</form>
<script>
document.formName.fieldName[2].value = "two";

function see(that) {
  const allFields = document.formName.fieldName;
  let fieldIndex = -1;
  
  // 遍历集合,找到和当前元素匹配的项
  for (let i = 0; i < allFields.length; i++) {
    if (allFields[i] === that) {
      fieldIndex = i;
      break;
    }
  }
  
  if (fieldIndex !== -1) {
    console.log(`当前获焦的是索引为 ${fieldIndex} 的字段`);
  }
}
</script>

原理说明

  • 当input触发onFocus事件时,this指向的就是当前获焦的那个input元素,把它传入see函数后,我们就可以用它来和表单里的所有同名input做对比。
  • document.formName.fieldName返回的是一个HTMLCollection(类数组对象),不是真正的数组,所以不能直接用数组的indexOf方法,需要先转成数组(方法一),或者用循环遍历(方法二)。

内容的提问来源于stack exchange,提问作者Trevor Turton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:09:31