从javascript更新html中的表格

时间:2018-05-29 03:21:06

标签: 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);

            }
        }
    }
}

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

以下是所有代码 -

<!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>

4 个答案:

答案 0 :(得分:1)

你想要这个:

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没有正确的值。

因此,我们将整个product-id作为字符串传递,并且它可以工作。

那么我们怎么能摆脱丑陋的逃脱字符串?

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

我认为将click事件绑定到容器,而renderoffunction外部会更漂亮。因为我们只需要一个监听器。而不是在每次调用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)

答案 1 :(得分:-1)

我认为您正在将product_name传递给addCart并针对product_id进行检查。

尝试放置debugger;并检查您在函数中获得的值。

答案 2 :(得分:-1)

试试这个,希望这有效:

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_id+", 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, cartItemId;
            if (cart.length > 0)
                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  + 1
                };
                cartItemId = cart.push(cartItem);
            }
        }
    }
    renderCartTable();
}

还要确保产品数组如下所示:

var products = [
    {product_id: 0, product_name: "item1", product_desc: "desc1", product_price: 100, product_qty: 0},
    {product_id: 1, product_name: "item2", product_desc: "desc2", product_price: 200, product_qty: 0},
    {product_id: 2, product_name: "item3", product_desc: "desc3", product_price: 300, product_qty: 0},
    {product_id: 3, product_name: "item4", product_desc: "desc4", product_price: 400, product_qty: 0}
];

答案 3 :(得分:-2)

函数不会对附加数据起作用,所以最好使用JQuery或其他东西,并按照这样做。

  $('#myTable').on('click','.addToCart',function(){
         //perform something...
  });

您也可以

  $(document).on('click','.addToCart',function(){
         //perform something...
  });