gpt4 book ai didi

javascript - 如何阻止一个innerHtml表格一遍又一遍地重复?

转载 作者:行者123 更新时间:2023-11-28 08:06:22 25 4
gpt4 key购买 nike

我创建了一个包含对象的数组,这些对象从三个不同的用户变量获取信息,但是其中一个有许多子变量,我不希望它在每次用户按下选择按钮时重复自身(其中更新表)而不是我希望它只是添加(或删除)表中已有的部分。谢谢(如果您需要变量代码请告诉我)请帮助!我真的需要一个解决方案!!

//creating array
var gProducts = new Array();
var gTotalCost = 0;



// Adding Products to array gProducts
function addProduct
{
var product = new Object();
product.name = name;
product.cost = cost;
gProducts.push(product);
gTotalCost += parseInt(cost)
}


//Getting products from array, use of for in loop setting new table rows in blank var for each array item
function renderProducts()
{
var HTMLadd = ""

for (var i in gProducts)
{
if( gProducts[i].cost > 0){
HTMLadd = HTMLadd +
"<tr>"+
"<td class='tableSettings00' id=tableRow2 >" + gProducts[i].name +
"</td>"+
"<td class='tableSettings'>€<span id=tableRow2part2>" + gProducts[i].cost +
"</span></td>"+
"</tr>";
}
else
{
}
}
document.getElementById('tableRow').innerHTML = HTMLadd;

}

最佳答案

在循环中,您总是迭代整个 gProducts ,因此每次执行该函数时,已放入表中的值都会加倍。

此示例使用 HTMLTableElement 中的一些方法创建新的行和单元格。它还有一个计数器 ( index ) 保存每次迭代的起始位置。

var index = 0; // Counter for holding the current position in gProducts

function renderProducts () {
var n, row, cell, span;
for (n = index; n < gProducts.length; n++) { // Start looping from the first new index in gProducts
if (gProducts[n].cost > 0) {
row = table.insertRow(-1); // Inserts a row to the end of table
cell = row.insertCell(-1); // Inserts a cell to the end of the newly-created row
cell.className = 'tableSettings00'; // Sets class for the cell
cell.id = 'tableRow' + index; // Sets an unique id for the cell
cell.innerHTML = gProducts[n].name; // Sets the content for the cell
cell = row.insertCell(-1); // Create another cell to row
cell.className = 'tableSettings';
cell.id = 'tableRowPart' + index;
cell.innerHTML = '€';
span = document.createElement('span'); // Creates an empty span element
span.id = 'tableRow2part' + index; // Sets an unique id for span
span.appendChild(document.createTextNode(gProducts[n].cost)); // Appends some text to the span
cell.appendChild(span); // Appends the span to the cell
}
}
index = n; // Sets counter equal to the length of gProducts
}

A live demo at jsFiddle .

作为旁注,我个人不喜欢使用 id s 表示表中的元素。如果id需要,您可能错误地构建了表格,或者数据不适合在表格中显示。

您可以使用索引和 table.rowsrows.cells集合来查找单元格,如果必须从单元格中搜索某些元素,请使用 firstElementChildnextElementSibling单元格的属性来找到它们。

关于javascript - 如何阻止一个innerHtml表格一遍又一遍地重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24744935/

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