if 语句以更改添加到添加数量的新行

If statement to change new row added to quantity added

本文关键字:添加 新行 if 语句      更新时间:2023-09-26

你好,我是这里的新手,所以如果我犯了任何格式或问题错误,请纠正我!

我正在尝试创建一个简单的购物篮文件,需要一些帮助来更改购物篮中的商品数量。目前,我可以创建一个按钮,将新行添加到表中并填充它,我只是在获取函数以检查该项目是否已在表中并且仅在更新数量单元格方面存在不足。我对 IF 语句毫无用处,所以任何帮助将不胜感激!

<!DOCTYPE html>
<html>
<head>
<script>
function additem1() {
    var table = document.getElementById("basket");
    var row1 = table.insertRow(1);
    var cell1 = row1.insertCell(0);
    var cell2 = row1.insertCell(1);
    var cell3 = row1.insertCell(2);
    var cell4 = row1.insertCell(3);
    var cell5 = row1.insertCell(4);
    var cell6 = row1.insertCell(5);
cell1.innerHTML = "Shorts (f)";
cell2.innerHTML = "Stone Wash";
cell3.innerHTML = "1";
cell4.innerHTML = "";
cell5.innerHTML = "";
cell6.innerHTML = "";
;
}
</script>
<style>
table, td {
    border: 1px solid black;
}
</style>
</head>
<body>
    <h2> List of Items </h2>
    <table border="1">
    <tr bgcolor="#9acd32">
        <th> Product </th>
        <th> Description </th>
        <th> Quantity </th>
        <th> Price </th>
            <tr>
    <td> Shorts (F) </td>
    <td> Stone wash Denim shorts </td>
    <td> 20 </td>
    <td> 25.90 </td>
    <td> <button onclick= "additem1()"> Add Item To Basket </button> </td>
     </table>


     <table id="basket" border = "1">
    <tr bgcolor="#9acd32">
        <th> Product </th>
        <th> Description </th>
        <th> Quantity </th>
        <th> Price </th>
        <th colspan="2"> Add / Remove items </th>
    </tr>
</table>

如您所见,第一个表保存项目信息,第二个表保存购物篮信息。

请考虑深入研究 js 编码;您可以考虑检查元素是否已经存在,如果是,则增加数量。

我让你的代码更通用一点,但对于一个工作篮子来说,还有更多的事情要做,那是你的工作。

法典:

function additem1(e) {
    var oRow = e.parentNode.parentNode
    var prod = oRow.cells[0].innerHTML;
    var des = oRow.cells[1].innerHTML;
    var table = document.getElementById("basket");
    var row1 = GetCellValues(prod);
    if (typeof row1 === 'undefined') {
        row1 = table.insertRow(1);
        var cell1 = row1.insertCell(0);
        var cell2 = row1.insertCell(1);
        var cell3 = row1.insertCell(2);
        var cell4 = row1.insertCell(3);
        var cell5 = row1.insertCell(4);
        var cell6 = row1.insertCell(5);
        cell1.innerHTML = prod;
        cell2.innerHTML = des;
        cell3.innerHTML = "1";
        cell4.innerHTML = "";
        cell5.innerHTML = "";
        cell6.innerHTML = "";;
    } else {
        row1.cells[2].innerHTML = parseInt(row1.cells[2].innerHTML) + 1
    }
}
function GetCellValues(prod) {
    var table = document.getElementById('basket');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            if (table.rows[r].cells[c].innerHTML == prod) return table.rows[r];
        }
    }
    return
}

演示:http://jsfiddle.net/85o9yz02/