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

如何将文本框输入值显示在嵌套Div中?错误排查与纯JS/HTML实现

问题分析与解决方案

你代码里的几个关键错误:

  • 你用document.getElementById('float-child')尝试获取元素,但float-child是class属性值,不是id,所以这个方法会返回null,无法拿到目标元素。
  • 你想获取输入框的内容,但却直接复制了整个子div的HTML结构,这不是你要的“显示输入值”的效果。
  • 第二个子div的id你写的是floatchild2,但实际该元素只有classfloat-child2,没有设置id,所以document.getElementById('floatchild2')也找不到元素。

当然可以仅用JavaScript和HTML实现需求,修正后的代码如下:

修正后的JavaScript

function onTransfer() {
  // 逐个获取每个输入框的当前值
  const firstName = document.getElementById('txtFname').value;
  const lastName = document.getElementById('txtLname').value;
  const age = document.getElementById('txtage').value;
  const email = document.getElementById('txtemail').value;

  // 整理要显示的内容格式
  const displayContent = `
    <p><strong>First Name:</strong> ${firstName}</p>
    <p><strong>Last Name:</strong> ${lastName}</p>
    <p><strong>Age:</strong> ${age}</p>
    <p><strong>Email Address:</strong> ${email}</p>
  `;

  // 给第二个子div设置id后,直接获取并插入内容
  document.getElementById('floatchild2').innerHTML = displayContent;
}

修正后的HTML(给第二个子div添加id)

<div class="float-container">
  <div class="float-child">
    <label> First Name:</label><input title="FirstName" id="txtFname" /><br>
    <label> Last Name:</label><input title="lastName" id="txtLname" /><br>
    <label> Age:</label><input title="age" id="txtage"><br>
    <label> Email Address:</label><input title="Email" id="txtemail" /><br>
    <button id="btnTransfer" onclick="onTransfer()">Transfer</button>
  </div>

  <!-- 添加id="floatchild2",方便JS获取 -->
  <div class="float-child2" id="floatchild2"></div>
</div>

说明

  1. 利用每个输入框已有的id,通过getElementById获取输入框的value属性,这才是用户输入的内容。
  2. 给第二个子div添加id,确保JS能准确找到目标元素。
  3. 将获取到的输入值整理成易读的HTML结构,插入到第二个子div中,实现“显示输入值”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:27:36