【发布时间】:2016-11-17 22:57:45
【问题描述】:
html
<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Javascript
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var otherCell = newRow.insertCell(2);
var check;
var myText = result.text;
var myTextTwo = myText.replace(/['"]+/g, '');
alert(myTextTwo);
for (var i = 0; i < tableRef.rows.length; i++) {
if (myTextTwo != tableRef.rows[i].cells[0].innerHTML) {
check = true
}
else if (myTextTwo == tableRef.rows[i].cells[0].innerHTML) {
tableRef.rows[i].cells[2].innerHTML += 1;
check = false;
break;
}
}
if (check) {
var newText = document.createTextNode(myTextTwo);
var otherText = document.createTextNode("1");
newCell.appendChild(newText);
otherCell.appendChild(otherText);
}
else {
alert("You have scanned this item before.");
}
我所做的是扫描包含产品 ID(例如“123”)的 QR,并将产品 ID 插入名为“产品 ID”的列中,我能够做到这一点。
但是,我现在要做的是,如果用户扫描包含相同产品 ID(例如“123”)的二维码,我的代码将能够检测到重复并添加到数量上。
所以我计划做的是遍历“产品 ID”列并检查是否有任何重复。如果没有任何重复,则 Product ID 的 Quantity 将为 1。
Product ID | Product Name | Quantity
123 | Hello | 1
否则存在重复,数量为2。
Product ID | Product Name | Quantity
123 | Hello | 2
【问题讨论】:
-
扫描得到什么价值或对象?
-
tableRef.rows[i].cells[0].innerHTML不是已经得到了你想要的吗? -
您需要将
innerHTML转换为数字,然后再加1。否则它将进行字符串连接,因此您将得到11而不是2。 -
我执行了我的代码并遇到了这个错误,IndexSizeError: Failed to execute 'insertCell' on 'HTMLTableRowElement': 提供的值 (2) 超出范围 [-1, 1]。
-
如果表最初是空的,你的循环将永远不会运行,所以你永远不会到达
check = true;。您应该将其初始化为true,然后在找到匹配项时将其设置为false。您不需要查找不匹配项的第一个if。
标签: javascript for-loop html-table