javascript - 从 javascript 更新 html 中的表

标签 javascript html html-table

我一直在尝试更新一个表,该表是一个“购物车”。但是,按下“添加到购物车按钮”后,我的表格不会更新。

javascript 的 html 仅使用 getElementbyId,当我运行 html 文件时,两个表都会出现在屏幕上。

我对 javascript 还很陌生,所以我希望有更多经验的人可以仔细检查我是否有我需要的东西。

var html = "<table border = '1|1' >";

html += "<td>Product Name</td>";
html += "<td>Product Description</td>";
html += "<td>Price</td>";
html += "<td>Add to Cart</td>";

for (var i = 0; i < products.length; i ++) {
    html += "<tr>";
    html += "<td>" + products[i].product_name + "</td>";
    html += "<td>" + products[i].product_desc + "</td>";
    html += "<td>" + products[i].product_price + "</td>";
    html += "<td>" + <button type = 'submit' onclick = 'addCart(products[i].product_name, this)'>Add to Cart</button> + "</td>";
    html += "</tr>";

}

html += "</table>";

document.getElementById("location1").innerHTML = html;


function addCart(product_id) {
    for (var i = 0; i < products.length; i++) {
        if (products[i].product_id == product_id) {
            var cartItem = null;
            for (var k = 0; k < cart.length; k++) {
                if (cart[k].product.product_id == products[i].product_id) {
                    cartItem = cart[k];
                    cart[k].product_qty++;
                    break;
                }
            }
            if (cartItem == null) {
                var cartItem = {
                    product: products[i],
                    product_qty: products[i].product_qty 
                };
                cart.push(cartItem);
            }
        }
    }
    renderCartTable();

}

//RenderCartTable & its functions
function addCart(product_id) {
    for (var i = 0; i < products.length; i++) {
        if (products[i].product_id == product_id) {
            var cartItem = null;
            for (var k = 0; k < cart.length; k++) {
                if (cart[k].product.product_id == products[i].product_id) {
                    cartItem = cart[k];
                    cart[k].product_qty++;
                    break;
                }
            }
            if (cartItem == null) {

                cartItem = {
                    product: products[i],
                    product_qty: products[i].product_qty 
                };
                cart.push(cartItem);

            }
        }
    }
}

代码从产品列表中提取,并生成一个表格,其中包含商品的名称、描述和价格以及“添加到购物车”按钮。该按钮用于将商品添加到称为“购物车”的不同列表中。
任何和所有的帮助表示赞赏。感谢您的宝贵时间!

下面是全部代码--

<!DOCTYPE html>
<html>
    <body>
        <br/>
        <p id="location1"> </p>
        <br/>
        <h2> Shopping Cart </h2>
        <p id="location2"> </p>
        <h2>Grand Total:</h2>
        <p id="location3"> </p>


        <script type="text/javascript", language="javascript", src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
            var products = [];
            var cart = [];

            //label individual products below in individual lists, and then have the product put through the product_setup function
            var product1 = ["Anvil", "Premium Grade Iron", 119.99];
            var product2 = ["Female Roadrunner Costume", "Guaranteed to attract Male Roadrunners", 54.99];

            function product_setup(product) {
                var productID = product[0];
                var product_desc = product[1];
                var qty = 1;
                var price = product[2];

                var newProduct = {
                    product_id: null,
                    product_desc: null,
                    product_qty: 0,
                    product_price: 0.00,
                };
                newProduct.product_id = productID;
                newProduct.product_desc = product_desc;
                newProduct.product_qty = qty;
                newProduct.product_price = price;


                products.push(newProduct);
            }

            product_setup(product1);
            product_setup(product2);    


            function product_table() {
                var html = "<table border = '1|1' >";

                html += "<td>Product Name</td>";
                html += "<td>Product Description</td>";
                html += "<td>Price</td>";
                html += "<td> </td>";


                for (var i = 0; i < products.length; i ++) {
                    html += "<tr>";
                    html += "<td>" + products[i].product_id + "</td>";
                    html += "<td>" + products[i].product_desc + "</td>";
                    html += "<td>" + products[i].product_price + "</td>";
                    html += "<td>" + "<button type = 'submit' onclick = 'addCart(products[i].product_id, this)'>Add to Cart</button>" + "</td>";
                    html += "</tr>";
                }

                html += "</table>";

                document.getElementById("location1").innerHTML = html;
            }
            product_table();

            function subtractQuantity(product_id) { 
                for (var i = 0; i < cart.length; i++) {
                    if (cart[i].product.product_id == product_id) {
                        cart[i].product_qty--;
                    }

                    if (cart[i].product_qty == 0) {
                        cart.splice(i,1);
                    }
                }
                renderCartTable();
            }

            function addQuantity(product_id) {
                for (var i = 0; i < cart.length; i++) {
                    if (cart[i].product.product_id == product_id) {
                        cart[i].product_qty++;
                    }  
                }
                renderCartTable();
            }

            function removeItem(product_id) {
                for (var i = 0; i < cart.length; i++) {
                    if (cart[i].product.product_id == product_id) {
                        cart.splice(i,1);
                    }
                }
                renderCartTable();
            }

            function renderCartTable() {
                var html = '';
                var ele = document.getElementById("location2");
                ele.innerHTML = ''; 

                html += "<table id='tblCart' border='1|1'>";
                html += "<tr><td>Product ID</td>";
                html += "<td>Product Description</td>";
                html += "<td>Quantity</td>";
                html += "<td>Price</td>";
                html += "<td>Total</td>";
                html += "<td>Action</td></tr>";
                var GrandTotal = 0;
                for (var i = 0; i < cart.length; i++) {
                    html += "<tr>";
                    html += "<td>" + cart[i].product.product_id + "</td>";
                    html += "<td>" + cart[i].product.product_desc + "</td>";
                    html += "<td>" + cart[i].product_qty + "</td>";
                    html += "<td>" + cart[i].product.product_price + "</td>";
                    html += "<td>" + parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty, 10) + "</td>";
                    html += "<td><button type='submit' onClick= 'subtractQuantity(\"" + cart[i].product.product_id + "\", this);'>Subtract Item</button> &nbsp <button type='submit' onClick='addQuantity(\"" + cart[i].product.product_id + "\", this);'/>Add Item</button> &nbsp<button type='submit' onClick='removeItem(\"" + cart[i].product.product_id + "\", this);'/>Remove Item</button></td>";
                    html += "</tr>";

                    GrandTotal += parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty, 10);
                }

                document.getElementById("location3").innerHTML = "$ " + GrandTotal;
                html += "</table>";
                ele.innerHTML = html;
            }
            renderCartTable();

            function addCart(product_id) {
                for (var i = 0; i < products.length; i++) {
                    if (products[i].product_id == product_id) {
                        var cartItem = null;
                        for (var k = 0; k < cart.length; k++) {
                            if (cart[k].product.product_id == products[i].product_id) {
                                cartItem = cart[k];
                                cart[k].product_qty++;
                                break;
                            }
                        }
                        if (cartItem == null) {

                            cartItem = {
                                product: products[i],
                                product_qty: products[i].product_qty 
                            };
                            cart.push(cartItem);

                        }
                    }
                }
                renderCartTable();
            }
        </script>
    </body>
</html>

最佳答案

你想要这个:

html += "<td>" + "<button type = 'submit' onclick = 'addCart(\"" + products[i].product_id + "\")'>Add to Cart</button>" + "</td>";

在您的情况下,单击按钮 onclick = 'addCart(products[i].product_id) 时, i里面products[i]仅在 product_table(){...} 内部已知所以当在上下文之外调用时, i未定义。尝试使用 this 传递上下文,虽然是个好主意,但 i里面就会知道addCart而不是调用 addCart 的地方(全局上下文或窗口),并且由于 for 循环继续 i不会有正确的值。

因此,我们将整个产品 ID 作为字符串传递,它就可以工作了。

那么我们如何摆脱丑陋的转义字符串呢?

模板文字几乎总是更漂亮 html += `<td><button type = 'submit' onclick = 'addCart("${products[i].product_id}")'>Add to Cart</button></td>`;但这是 ES6 功能(因此请检查您需要支持哪些浏览器)。

我认为将点击事件绑定(bind)到容器,并且在渲染函数之外会更漂亮。因为这样我们只需要一名听众。与每次调用renderCartTable时创建新的onclicks相反.

var clickHandler = function(evt){
    if(evt.target.nodeName === 'BUTTON'){
      // Check that we have the right button (from a class perhaps)
      // parse out data from event.target.parentElement
      // or pass in product-id via a data attribute
    }
};
document.getElementById("location1").addEventListener('click', clickHandler)

关于javascript - 从 javascript 更新 html 中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50575869/

相关文章:

javascript - 动画圆描边 SVG - 不是一个完整的圆

javascript - Riot.js 使用 css 库作为标签或组件

html - 单击后围绕 div 突出显示烦人的蓝色

html - 如何使用单元格中移动的内容控制表格行高

javascript - Javascript 如何导致 IE 8 在兼容性 View 中重新加载页面?

javascript - 如何将 id 发送到 refs(forwardrefs) 到子组件

javascript - 如何使用 jquery 从 html 中的表格单元格中检索值?

php - 向 CSS 表格添加样式

html - 我的 ".hours"在 Chrome 中显示不正确。但是,在 Atom 中它显示正常。可能是什么问题?

CSS DIV定位和边框问题