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

如何实现点击按钮后在用户文本中随机插入7个输入框

前端功能实现问题:随机替换文本中的单词为输入框

需求:用户在输入框输入文本后点击按钮,系统将文本展示在h1元素中,同时随机把文本里的7个单词替换成输入框(同一文本内完成7次替换)。以下是我写的代码,但没达到预期效果:

function myFunction() {
  var x = document.getElementById("input").value;
  x = x + " ";
  var y = document.getElementById("inputed");
  var a,b = "c";
  const c=[];
  const d=[];
  var e;
  var f = 0;
  const array = [];
  const z = x.length;
  for (let index = 0; index < 7; index++) {
    a= "c";
    b= "c";
    c.push(0);
    d.push(0);
    c[index] = 0;
    d[index] = 0;
    e = 1;
    f = 0;
    // 获取随机空格位置及后续的空格
    while (a != " ") {
      c[index] = Math.floor(Math.random() * x.length - 2);
      a = x.charAt(c[index]);
    }
    d[index] = c[index];
    // d从c的位置开始递增,直到找到下一个空格
    while (b != " ") {
      d[index]++;
      b = x.charAt(d[index]);
    }
    // 期望拼接内容:0到c[0]的文本 + 输入框 + d[0]到c[1]的文本 + 输入框,直到7次替换
    y.innerHTML = `${x.slice(
      0,
      c[0]
    )}<input type="text" style="color: gray;border:2px solid;border-radius: 10px;outline: none;
font-size: x-large;height:40px;width: 100px;" >${x.slice(d[0], z)} `;
  }
}

问题分析

  • 每次循环直接覆盖y.innerHTML,最终仅显示最后一次替换结果,无法累积7次替换效果
  • 通过空格定位单词的逻辑存在漏洞,连续空格、文本首尾空格都会导致选到无效位置
  • 变量命名混乱,循环内重复初始化数组元素的操作无意义,逻辑冗余

解决方案

核心思路:先将文本分割为单词数组,随机选中7个不重复的单词位置进行替换,最后拼接成完整HTML插入到h1中。

完整代码示例(包含HTML结构):

<!-- HTML部分 -->
<input type="text" id="input" placeholder="输入文本">
<button onclick="myFunction()">生成带输入框的文本</button>
<h1 id="inputed"></h1>

<script>
function myFunction() {
  const inputText = document.getElementById("input").value.trim();
  const targetH1 = document.getElementById("inputed");
  
  // 处理空输入
  if (!inputText) {
    targetH1.innerHTML = "";
    return;
  }

  // 将文本分割为单词数组,保留空格作为分隔符(兼容多空格场景)
  const words = inputText.split(/(\s+)/);
  // 筛选出所有非空格的单词索引
  const wordIndices = words.reduce((acc, item, idx) => {
    if (!/\s+/.test(item)) acc.push(idx);
    return acc;
  }, []);

  // 确定替换数量:最多7个,若单词数不足则取全部
  const replaceCount = Math.min(7, wordIndices.length);
  // 随机选出不重复的单词索引
  const selectedIndices = [];
  while (selectedIndices.length < replaceCount) {
    const randomIdx = wordIndices[Math.floor(Math.random() * wordIndices.length)];
    if (!selectedIndices.includes(randomIdx)) {
      selectedIndices.push(randomIdx);
    }
  }

  // 将选中的单词替换为输入框
  const result = [...words];
  selectedIndices.forEach(idx => {
    result[idx] = `<input type="text" style="color: gray;border:2px solid;border-radius: 10px;outline: none;font-size: x-large;height:40px;width: 100px;">`;
  });

  // 拼接成HTML并插入到h1
  targetH1.innerHTML = result.join("");
}
</script>

代码说明

  1. 分割文本时保留空格分隔符,避免替换后丢失原有的空格格式
  2. 仅筛选非空格的单词索引,确保只替换真正的单词
  3. 随机选择不重复的索引,避免重复替换同一个单词
  4. 一次性拼接并插入HTML,避免多次覆盖innerHTML导致的无效操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:05:13