首页 > 解决方案 > 如何在网页中创建动态表格

问题描述

我正在尝试学习如何创建带有“动态”表格的网页。我在创建网页方面的经验为零,但我仍然能够通过使用 html 来构造表格的形状(下图是非常基础版本中的非常基础的图像):

在此处输入图像描述

总结一下,假设我希望网页允许您使用键盘作为输入手动引入 A、B、... J,它应该自动显示 K 列中所有行的总和。我没有知道我应该使用什么技术/代码... javascript?php?我在python方面有很好的技能,它可以以某种方式帮助吗?我想尽快完成。

提前致谢

标签: htmldataframeweb

解决方案


您可以通过手动创建表并添加监听表输入变化的事件监听器来做到这一点。然后,您可以使用表输入的值来计算输出并将其显示在 K 列中:

const inputs = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
// Get the output column
const output = document.getElementById('output');

// Calculate the total from all inputs
function calculate() {
  // Start with zero
  let total = 0;
  // For each element, get the value and add it to total.
  inputElements.forEach(inputElement => {
    // If the element does not have a value, we just add 0 (this is what the "|| 0" is for)
    total += Number(inputElement.value) || 0;
  });
  // Display the total in the output column
  output.innerHTML = total;
}

// Get all the input columns
const inputElements = inputs.map(input => document.getElementById(`input-${input}`));
// Add Event Listeners to all the input columns
inputElements.forEach(inputElement => inputElement.addEventListener('change', calculate));
table input {
  width: 45px;
}
<table id="container">
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
      <th>H</th>
      <th>I</th>
      <th>J</th>
      <th>K</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input id="input-A" type="number" /></td>
      <td><input id="input-B" type="number" /></td>
      <td><input id="input-C" type="number" /></td>
      <td><input id="input-D" type="number" /></td>
      <td><input id="input-E" type="number" /></td>
      <td><input id="input-F" type="number" /></td>
      <td><input id="input-G" type="number" /></td>
      <td><input id="input-H" type="number" /></td>
      <td><input id="input-I" type="number" /></td>
      <td><input id="input-J" type="number" /></td>
      <td id="output"></td>
    </tr>
  </tbody>
</table>


推荐阅读