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

如何在多步骤表单中使用用户输入的名字实现个性化提问?

多步骤表单个性化文本实现方案

先给你的HTML做一点小修改,给关键元素加上ID,方便JS精准定位:

<form action="">
  <div class="section1">
    <input type="text" id="firstNameInput" placeholder="First Name">
    <button type="button" class="next-btn" id="step1Next">Next</button>
  </div>
  <br>
  <div class="section2" style="display: none;">
    <p id="ageQuestion">[First Name], What's your age?</p>
    <input type="number" class="age" placeholder="Your Age">
    <button type="button" class="next-btn" id="step2Next">Next</button>
  </div>
  <br>
  <div class="section3" style="display: none;">
    <p id="statusQuestion">Are you doing good [First Name]?</p>
    <input type="text" class="good" placeholder="Yes or No ?">
    <button class="submit">submit</button>
  </div>
</form>

然后把这段JS代码放在HTML的</body>标签前面就行:

// 获取需要操作的页面元素
const firstNameInput = document.getElementById('firstNameInput');
const step1NextBtn = document.getElementById('step1Next');
const section2 = document.querySelector('.section2');
const ageQuestion = document.getElementById('ageQuestion');
const section3 = document.querySelector('.section3');
const statusQuestion = document.getElementById('statusQuestion');
const step2NextBtn = document.getElementById('step2Next');

// 第一步"Next"按钮的点击逻辑
step1NextBtn.addEventListener('click', function() {
  // 获取输入的名字,去掉前后多余空格
  const userName = firstNameInput.value.trim();
  if (userName) {
    // 替换第二步的提问文本
    ageQuestion.textContent = `${userName}, What's your age?`;
    // 切换显示状态:隐藏第一步,显示第二步
    document.querySelector('.section1').style.display = 'none';
    section2.style.display = 'block';
  } else {
    alert('请输入你的名字');
  }
});

// 第二步"Next"按钮的点击逻辑
step2NextBtn.addEventListener('click', function() {
  const userName = firstNameInput.value.trim();
  // 替换第三步的提问文本
  statusQuestion.textContent = `Are you doing good ${userName}?`;
  // 切换显示状态:隐藏第二步,显示第三步
  section2.style.display = 'none';
  section3.style.display = 'block';
});

关键细节说明

  • 给按钮加了type="button",避免默认触发表单提交的行为
  • 默认隐藏第二步、第三步,点击下一步再显示,体验更贴合多步骤表单的逻辑
  • 用trim()处理输入的名字,防止空输入或只输入空格的情况
  • 用模板字符串${userName}拼接文本,比传统字符串拼接更直观好写

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:00:05