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

如何在JavaScript中让函数将输入值同步到多个同ID div元素?

解决多元素填充输入值的问题

首先要明确:HTML规范要求页面内的id必须唯一,你当前多个<span>使用了相同的id(如Answer1),这是不符合标准的写法,也是getElementById()仅返回第一个匹配元素的原因。正确的做法是用class来标记需要填充的元素,再通过JS批量操作这些元素。

修改后的完整代码

HTML(修正重复id为class)

<p class="Questionstyle">This is Question #1</p>
<input type="text" id="Question1" class="input-box" name="fname"><br>

<p class="Questionstyle">This is Question #2</p>
<input type="text" id="Question2" class="input-box" name="fname"><br>

<p class="Questionstyle">This is Question #3</p>
<input type="text" id="Question3" class="input-box" name="fname"><br>

<button class="createbutton" onclick="fillAllAnswers()">Create</button>

<br>
<br>
<div id="Result" class="Resultstyle">
    <p>This is answer of question #1 : 
        <span class="answer answer-1" style="color: blue;"></span>
        And then we have answer of question #2 : 
        <span class="answer answer-2" style="color: blue;"></span>
        Then answer of question #3 : 
        <span class="answer answer-3" style="color: blue;"></span>
        And here we have answer of question #1 again : 
        <span class="answer answer-1" style="color: blue;"></span> 
        and also answer of question #2 again : 
        <span class="answer answer-2" style="color: blue;"></span> 
        Then answer of question #3 again : 
        <span class="answer answer-3" style="color: blue;"></span>.
    </p>
</div>

JavaScript(优化为通用批量填充函数)

// 根据问题编号,批量填充对应答案元素
function fillAnswer(questionNum) {
  const inputValue = document.getElementById(`Question${questionNum}`).value;
  // 获取所有对应class的答案元素
  const answerElements = document.querySelectorAll(`.answer-${questionNum}`);
  // 遍历设置每个元素的内容
  answerElements.forEach(element => {
    element.innerHTML = inputValue + " ";
  });
}

// 点击按钮时执行所有填充操作
function fillAllAnswers() {
  fillAnswer(1);
  fillAnswer(2);
  fillAnswer(3);
}

CSS(无需修改,保持原样式)

.input-box {
  width: 50%;
  padding: 7px 10px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 1px solid black;
  border-radius: 5px;
}

.createbutton {
  background-color: #4b83fc;
  border: none;
  border-radius: 8px;
  color: white;
  padding: 8px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  cursor : pointer;
}

.Questionstyle {
    font-size: 15px;
    line-height: 5px;
}

.Resultstyle {
    font-size: 20px;
    line-height: 30px;
}

关键说明

  1. 替换重复id为class:用answer-1、answer-2这类class标记同组答案元素,符合HTML规范,同时方便批量选择。
  2. 使用querySelectorAll():该方法能获取所有匹配CSS选择器的元素,返回的NodeList支持forEach循环遍历,实现批量赋值。
  3. 函数复用:将重复的填充逻辑封装为通用函数,减少冗余代码,后续新增问题只需调用fillAnswer(编号)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:54:22