gpt4 book ai didi

javascript - 如何在 document.getelementById 中尝试 null.value

转载 作者:行者123 更新时间:2023-12-03 00:54:36 24 4
gpt4 key购买 nike

我有一个表,其中包含动态行,我需要获取数据并对其进行计算,以便获得 Javascript 中的总行数并在其中运行循环。我的 table 看起来像这样

<table id='mytable1'>
<tr>
<td id="name_1">Precious Metals</td>
<td id="price_1">500</td>
<td id="qty_1">10</td>
</tr>
<tr>
<td id="name_2">Non Precious Metals</td>
<td id="price_2">200</td>
<td id="qty_2">5</td>
</tr>
<tr>
<td id="name_3">Gemstones</td>
<td id="price_3">300</td>
<td id="qty_3">10</td>
</tr>

我的 JavaScript 看起来像这样

<script>

var counter = $('#mytable1 tr').length;
for (i = 1; i <= counter; i++) {
var price = document.getElementById('price_'+i).value;
var qty= document.getElementById('qty'+i).value;
var price_calc = price * qty;
var total_price = total_price + price_calc;
}
</script>

问题是,如果丢失了一行,我的意思是管理员删除了第 2 行,现在将有两行,当循环运行并且没有找到第 2 行时,它会抛出错误。请帮助我或指导我如何解决这个问题

最佳答案

您可以简化 HTML 并使计算独立于表中的行数。最重要的是,jQuery 不是必需的。

源代码中的文档。

const table = document.getElementById("mytable1");
// Put all existing rows inside the table in an array
const rows = [...table.getElementsByTagName("tr")];
// Loop through all rows
rows.map( row => {
// Price is in the first cell
const price = parseInt(row.cells[1].innerHTML);
// Quantity is in the second cell
const quantity = parseInt(row.cells[2].innerHTML);
// Calculate total value for each row
const total_price = price * quantity;
console.log(total_price);
});
<table id='mytable1'>
<tr>
<td>Precious Metals</td>
<td>500</td>
<td>10</td>
</tr>
<tr>
<td>Non Precious Metals</td>
<td>200</td>
<td>5</td>
</tr>
<tr>
<td>Gemstones</td>
<td>300</td>
<td>10</td>
</tr>
</table>

关于javascript - 如何在 document.getelementById 中尝试 null.value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52890593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com