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

如何使用JavaScript通过ID获取数据并填充到HTML表格单元格中

存在的问题

你原来的代码存在以下几处错误,导致无法实现预期效果:

  • 事件名不匹配:下拉框的onchange属性写的是gettingList(),但实际定义的函数名是getList,选择商品后价格无法填充到对应输入框
  • ID对应错误:计算总金额的逻辑里,要赋值的目标元素ID写的是bill,但实际总金额输入框的ID是result,计算后的值无法正常显示
  • 表格行插入位置错误:insertRow(0)会把新行插入到表格最顶部,会出现在表头上方,应该用insertRow(-1)插入到表格最后一行
  • 单元格赋值语法错误:给单元格赋值时多写了多余的小数点,且没有使用正确的内容属性,需要用textContent填充单元格内容
  • 商品名取值错误:itemsList.value拿到的是商品的价格属性,需要获取选中option的文本内容才能得到商品名称

修复后的完整代码

<select id="itemsList" onchange="getList()">
    <option>Please select the option</option>
    <option value="50">Soap</option>
    <option value="100">Sugar</option>
    <option value="290">Oil</option>
</select>
<br><br>

<input type="number" id="price" disabled="">
<br><br>

<input type="number" id="quantity" onChange="calculate()">
<br><br>

<input type="number" id="result">

<button type="button" onclick="addDetails()">Add</button>

<table id="myTable" border="1">
  <tr>
    <th>Product Name</th>
    <th>Price</th>
    <th>Quantity</th>
    <th>Amount</th>
  </tr>
</table>
<br>

<script>
var getPrice = document.getElementById('itemsList');

function getList () {
    document.getElementById('price').value = getPrice.value;
}

function calculate () {
    var prc = document.getElementById('price').value;
    var qty = document.getElementById('quantity').value;
    var result = prc * qty;
    document.getElementById('result').value = result;
}

function addDetails () {
    var table = document.getElementById("myTable");
    var row = table.insertRow(-1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var selectedItem = getPrice.options[getPrice.selectedIndex].text;
    cell1.textContent = selectedItem;
    cell2.textContent = document.getElementById('price').value;
    cell3.textContent = document.getElementById('quantity').value;
    cell4.textContent = document.getElementById('result').value;
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:54:03