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

如何批量将多个ATTR对应内容统一替换为相同CONTENT值

多输入字段批量替换内容实现方案

你期望的ATTR=ID1, ID2, ID3 CONTENT=newContent格式指令,可以通过「指令解析+批量DOM操作」两步实现,具体逻辑如下:

  • 指令解析:把传入的指令字符串按规则拆分,先提取ATTR=后、CONTENT=前的部分,按逗号分割、去除前后空格后得到所有目标输入框的ID列表;再提取CONTENT=后的全部内容,作为要统一替换的目标值。
    注意:解析时取第一个CONTENT=的位置做截断,是为了兼容替换内容本身包含CONTENT=字符的场景,避免解析出错。
  • 批量赋值:遍历所有拿到的目标ID,找到对应DOM元素后统一设置输入值即可,兼容普通input、textarea等各类可输入字段。

可直接复用的实现代码

function runBatchReplace(command) {
  // 定位CONTENT=关键字的位置
  const contentSplitIndex = command.indexOf('CONTENT=');
  // 提取ID段
  const attrSection = command.slice(0, contentSplitIndex);
  // 提取替换内容段
  const replaceValue = command.slice(contentSplitIndex + 8).trim();
  // 处理ID列表:去空格、过滤空值
  const targetIds = attrSection
    .replace('ATTR=', '')
    .split(',')
    .map(id => id.trim())
    .filter(id => id.length > 0);
  // 批量赋值
  targetIds.forEach(id => {
    const el = document.getElementById(id);
    if (el && 'value' in el) {
      el.value = replaceValue;
      // 适配React/Vue等框架的状态同步,不需要可以删掉
      el.dispatchEvent(new Event('input', { bubbles: true }));
    }
  })
}

// 调用示例,直接传入你定义格式的指令即可
runBatchReplace('ATTR=ID1, ID2, ID3 CONTENT=newContent')

适配扩展说明

  • 如果你需要按class、name等其他属性匹配元素,只需要修改元素获取逻辑,替换为document.querySelectorAll对应选择器即可。
  • 如果需要支持非输入元素的文本替换,把el.value = replaceValue改为el.textContent = replaceValue即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:18:21