gpt4 book ai didi

javascript - 循环遍历我的表的特定列

转载 作者:行者123 更新时间:2023-12-03 06:35:20 25 4
gpt4 key购买 nike

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”列并检查是否有重复项。如果没有任何重复项,则产品 ID 的数量将为 1。

Product ID | Product Name | Quantity
123 | Hello | 1

否则,存在重复,数量将为 2。

Product ID | Product Name | Quantity
123 | Hello | 2

最佳答案

你的意思是这样吗?

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];

// save the row number of the existing product
var found = false;
var myText = result.text;
var myTextTwo = myText.replace(/['"]+/g, '');

// search the table for the existing product
for (var i = 0; i < tableRef.rows.length && !found; ++i) {
// if you found it then
if (tableRef.rows[i].cells[0].innerHTML == myTextTwo) {
// update the value
tableRef.rows[i].cells[2].innerHTML += 1;

// and say we found it
found = true;
}
}

// at this point, if we didn't find anything then add a new row
if (!found) {
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.insertCell(0).innerText = "...";
newRow.insertCell(0).innerText = "...";
newRow.insertCell(0).innerText = 1;
}

<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>

</tbody>
</table>

关于javascript - 循环遍历我的表的特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38250910/

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