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

页面加载时自动将HTML表格值填充至对应文本框的实现方法

实现页面刷新时自动将表格值填入文本框

你需要移除点击触发的逻辑,改为在页面加载完成后直接读取表格内容并赋值给文本框。原代码的问题在于选择了tbody元素而非具体的单元格,且依赖点击事件触发,无法自动执行。

解决方案代码

你可以把这段JavaScript代码放在HTML的</body>标签之前,或者用DOMContentLoaded事件确保DOM加载完成后执行:

// 等待页面DOM完全加载后执行
document.addEventListener('DOMContentLoaded', function() {
  // 获取表格里的所有单元格
  const tableCells = document.querySelectorAll('#myTbl tbody td');
  // 获取两个文本框元素
  const txtInput = document.getElementById('txt');
  const txt2Input = document.getElementById('txt2');

  // 给文本框赋值,确保存在对应单元格时才操作
  if (tableCells.length >= 2) {
    txtInput.value = tableCells[0].textContent.trim();
    txt2Input.value = tableCells[1].textContent.trim();
  }
});

代码说明

  • DOMContentLoaded事件:保证代码在页面所有DOM元素渲染完成后执行,避免出现找不到元素的情况。
  • querySelectorAll('#myTbl tbody td'):精准定位表格tbody下的所有单元格,拿到包含值1和2的两个td元素。
  • 通过索引[0]和[1]分别获取第一个和第二个单元格的内容,调用trim()是为了去除可能存在的空白字符。
  • 增加长度判断是为了避免表格结构变化时出现报错。

完整HTML示例

如果把代码整合到HTML中,结构如下:

<table id="myTbl">
   <thead>
     <tr>
       <th>A</th>
       <th>B</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
 </tbody>
</table>
<input type="text" name="txt" id="txt" >
<input type="text" name="txt" id="txt2" >

<script>
document.addEventListener('DOMContentLoaded', function() {
  const tableCells = document.querySelectorAll('#myTbl tbody td');
  const txtInput = document.getElementById('txt');
  const txt2Input = document.getElementById('txt2');

  if (tableCells.length >= 2) {
    txtInput.value = tableCells[0].textContent.trim();
    txt2Input.value = tableCells[1].textContent.trim();
  }
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:00:59