何时使用 $ .each 从 table 的行中获取重复值

When to use $ .each get duplicate values ​from the rows of a table

早上好,我想获取table中的所有记录并将它们添加到一个数组中,然后使用ajax将它们注册到数据库中。 我遇到的问题是使用 .each 我正确地得到了第一行的值,但是当添加另一行时,数组最终重复了。
我分享一些图片以便更好地理解我的问题
debugging the first row of the table

duplicates

all duplicate table rows

Javascript

function AgregarLista() {
    const TD = $('<td></td>');
    const TR = $('<tr></tr>');
    const TABLE_VENTA = $('#dtVenta');
    const PRODUCT_TOTAL = $('#TotalPagar');
    let item = 0;
    $('#btnAgregarTabla').click(function () {
        item++;
        let id_cliente = $('#id_cliente').val();
        let id_producto = $('#id_producto').select2('val');
        let precio_producto = $('#precio').val();
        let stock_producto = $('#stock').val();
        let cantidad_producto = $('#cantidad').val();
        let subtotal_producto = parseInt(precio_producto) * parseInt(cantidad_producto);

        let nro_venta = TD.clone().html(item).addClass('nro_sale');
        let cliente = TD.clone().html(id_cliente).addClass('td_customer');
        let producto = TD.clone().html(id_producto).addClass('td_product');
        let precio = TD.clone().html(precio_producto).addClass('td_price');
        let stock = TD.clone().html(stock_producto).addClass('td_stock');
        let cantidad = TD.clone().html(cantidad_producto).addClass('td_quantity');
        let preciototal = TD.clone().html(subtotal_producto).addClass('subtotal');

        let newRow = TR.clone().append(nro_venta, cliente, producto, precio, stock, cantidad, preciototal);

        let total = subtotal_producto;
        $('.subtotal').each(function (index, tr) {
            total = total + parseInt($(this).text());
        });

        TABLE_VENTA.find('tbody').append(newRow);
        PRODUCT_TOTAL.find('#total_pagar').val(total);

//*===========================================================  
//* here I call the method I use to get the array  
//* ==========================================================

        loopDetailTable();
    });
}  

通过这段代码我得到了table行的值

// * ==============================================
//* With this code I get the values ​​of the table rows
// * ==============================================
function loopDetailTable(params) {
    let index = 0;
    var obj = new Object();
    obj.DetailsList = [];
    $('#dtVenta').each(function () {
        let item_detalle = new Object();
        item_detalle.vNumero = $('.nro_sale').text();
        item_detalle.cID = $('.td_customer').text();
        item_detalle.pID = $('.td_product').text();
        item_detalle.pPrice = $('.td_price').text();
        item_detalle.pStock = $('.td_stock').text();
        item_detalle.pQuantity = $('.td_quantity').text();
        item_detalle.pSubtotal = $('.subtotal').text();
        obj.DetailsList[index] = item_detalle;
        index++;
        console.log(obj);
    });
    return obj;
}  

HTML形式

<div class="d-flex">
    <div class="col-md-5">
        <form role="form">
            <div class="card">
                <div class="card-body">
                    <h5>Datos del cliente:</h5>
                    <div class="form-group d-flex">
                        <div class="col-md-6 d-flex">
                            <input type="text" name="dni" id="dni" class="form-control" placeholder="dni cliente">
                            <input type="button" id="btnBuscarCliente" value="Buscar" class="btn btn-outline-danger">
                        </div>
                        <div class="col-md-6">
                            <input type="hidden" name="id_cliente" id="id_cliente" value="">
                            <input type="text" name="nombre_cliente" id="nombre_cliente" value="" class="form-control" placeholder="Cliente" disabled>
                        </div>
                    </div>
                    <h5>Datos del producto:</h5>
                    <div class="form-group d-flex">
                        <div class="col-md-6 d-flex">
                            <!-- <input type="text" name="id_producto" id="id_producto" class="form-control" placeholder="codigo producto"> -->
                            <select name="id_producto" id="id_producto" class="id_producto js-states form-control"></select>
                            <input type="button" id="btnBuscarProducto" value="Buscar" class="btn btn-outline-danger">
                        </div>
                        <div class="col-md-6">
                            <input type="text" name="nombre_producto" id="nombre_producto" class="form-control" placeholder="Producto" disabled>
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-md-4">
                            <input type="text" name="precio" id="precio" class="form-control" placeholder="s/.0.00" disabled>
                        </div>
                        <div class="col-md-4">
                            <input type="number" name="stock" id="stock" class="form-control" placeholder="stock" disabled>
                        </div>
                        <div class="col-md-4">
                            <input type="number" name="cantidad" id="cantidad" value="1" class="form-control" placeholder="cantidad">
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <input type="button" id="btnAgregarTabla" value="Agregar" class="btn btn-primary float-right">
                </div>
            </div>
        </form>
    </div>
    <div class="col-md-7">
        <div class="card">
            <div class="card-body">
                <div class="d-flex col-md-6 ml-auto">
                    <label class="mx-3 mt-1">Nro.serie:</label>
                    <input type="text" name="nro_serie" id="nro_serie" th:value="${serie}" class="form-control">
                </div>
                <table id="dtVenta" class="table mt-4" style="width: 100%;">
                    <thead>
                        <tr>
                            <th>Nro.Venta</th>
                            <th>Cliente</th>
                            <th>Producto</th>
                            <th>Precio</th>
                            <th>Stock</th>
                            <th>Cantidad</th>
                            <th>SubTotal</th>
                        <tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div id="TotalPagar" class="card-footer">
                <div class="row">
                    <input type="button" id="btnCancelarVenta" value="Cancelar" class="btn btn-danger">
                    <input type="button" id="btnGenerarVenta" value="Generar" class="btn btn-success mx-1">
                    <div class="d-flex ml-auto">
                        <label for="" class="mx-2 mt-1">Total:</label>
                        <input type="text" name="total_pagar" id="total_pagar" class="form-control">
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>  

谢谢大家的帮助,问候。

你得到 'duplicates' 因为 selector。您 select 使用 class 名称,这些名称不是唯一的。例如 $('.td_customer').text(); select 所有客户单元。 你不想要的。您只需要某一行的客户单元格。 我认为你可以通过遍历 table 行来解决你的问题(你用 id dtVenta 遍历 tables,那只是一个 table)。

所以尝试这样的事情:

$('#dtVenta tr').each(function () {
        // $(this) is the 'current' row of the table
        let item_detalle = new Object();
        item_detalle.vNumero = $(this).find('.nro_sale').text(); // find all child .nro_sale cells and get it's text
        item_detalle.cID = $(this).find('.td_customer').text();
        item_detalle.pID = $(this).find('.td_product').text();
        item_detalle.pPrice = $(this).find('.td_price').text();
        item_detalle.pStock = $(this).find('.td_stock').text();
        item_detalle.pQuantity = $(this).find('.td_quantity').text();
        item_detalle.pSubtotal = $(this).find('.subtotal').text();
        obj.DetailsList[index] = item_detalle;
        index++;
        console.log(obj);
    });