Javascript 如何阻止innerHtml表一次又一次地重复自身?
我制作了一个数组,其中包含从三个不同的用户变量获取信息的对象,然而,在其中一个变量上有许多子变量,我不希望每次用户按下select按钮时它都会重复,而select按钮会更新表格,我希望它只是添加或删除表格中已有的部分。谢谢如果您需要变量代码,请告诉我,请帮助!!我真的需要一个解决方案Javascript 如何阻止innerHtml表一次又一次地重复自身?,javascript,html,arrays,innerhtml,for-in-loop,Javascript,Html,Arrays,Innerhtml,For In Loop,我制作了一个数组,其中包含从三个不同的用户变量获取信息的对象,然而,在其中一个变量上有许多子变量,我不希望每次用户按下select按钮时它都会重复,而select按钮会更新表格,我希望它只是添加或删除表格中已有的部分。谢谢如果您需要变量代码,请告诉我,请帮助!!我真的需要一个解决方案 //creating array var gProducts = new Array(); var gTotalCost = 0; // Adding Products to array gProducts
//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,因此,每次执行函数时,已经放置到表中的值都会加倍 此示例使用中的一些方法创建新行和单元格。它还有一个计数器索引,用于保存每次迭代的起始位置
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
}
作为旁注,我个人不喜欢对表中的元素使用ID。如果需要ID,则可能是表构造不正确,或者数据不适合显示在表中
您可以使用index和table.rows和rows.cells集合查找单元格,如果必须从单元格中搜索某些元素,请使用单元格的firstElementChild和nextElementSibling属性查找它们。这是谷歌翻译的问题吗?我能听懂每一个单词,但我不知道它们放在一起是什么意思。我不知道getElementById'tableRow'是什么,但听起来像是一个表格行。用一堆其他表行替换其内部HTML是不明智的。你将使你的HTML无效。你不应该在数组中使用for-in循环。这可能是部分原因。而是用于var i=0;i