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

使用querySelectorAll与addEventListener获取交互元素序号及对应变量

关联同序号输入框的值同步问题

问题场景

现有如下HTML结构:

<form name="form" ..>
  <input type="text" name="title1" id="title1" class="f_title" value="smth LV">
  <input type="text" name="title2" id="title2" class="f_title" value="smth EN">
  <input type="text" name="title3" id="title3" class="f_title" value="smth DE">

  <input type="text" name="url1" id="url1" class="f_url" value="smth-lv">
  <input type="text" name="url2" id="url2" class="f_url" value="smth-en">
  <input type="text" name="url3" id="url3" class="f_url" value="smth-de">
</form>

需求是:用户修改class为f_title的输入框时,将处理后的值同步到对应序号的f_url输入框中。比如修改title2,就要把处理后的值设置到url2里。

当前尝试的代码无法在事件回调中正确获取元素序号并引用对应url输入框:

let i = 1;
document.querySelectorAll('.f_title').forEach(el => {
 el.addEventListener('change', () => {

  if (typeof form.url[i] !== 'undefined') {
    // 这里无法正确拿到对应序号的url输入框
    form.url[i] = form.title[i].value;
  }

 });
 i++;
});

解决方法

这里提供三种规范的实现方式,都不用eval:

方法1:利用forEach的索引参数

forEach的第二个参数是元素在集合中的索引(从0开始),加1就是对应的序号,通过表单的属性访问器获取对应url输入框:

document.querySelectorAll('.f_title').forEach((el, index) => {
  el.addEventListener('change', () => {
    const seq = index + 1;
    const urlInput = form['url' + seq]; // 用属性名拼接的方式获取输入框
    if (urlInput) {
      // 这里写你的值处理逻辑,示例:转小写+空格换横杠
      const processedValue = el.value.toLowerCase().replace(/\s+/g, '-');
      urlInput.value = processedValue;
    }
  });
});

方法2:从输入框的id/name提取序号

直接从元素自身的id或name属性里匹配数字部分,不依赖遍历顺序:

document.querySelectorAll('.f_title').forEach(el => {
  el.addEventListener('change', () => {
    // 匹配id/name里的数字序号
    const numMatch = el.id.match(/\d+/);
    if (!numMatch) return;
    
    const seq = numMatch[0];
    const urlInput = form['url' + seq];
    if (urlInput) {
      const processedValue = el.value.toLowerCase().replace(/\s+/g, '-');
      urlInput.value = processedValue;
    }
  });
});

方法3:通过数组索引一一对应

把f_title和f_url分别转为数组,利用索引直接对应:

const titleInputs = document.querySelectorAll('.f_title');
const urlInputs = document.querySelectorAll('.f_url');

titleInputs.forEach((el, index) => {
  el.addEventListener('change', () => {
    const urlInput = urlInputs[index];
    if (urlInput) {
      const processedValue = el.value.toLowerCase().replace(/\s+/g, '-');
      urlInput.value = processedValue;
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:33:22