繁体   English   中英

JS Array 实现购物车的问题

[英]JS Array problem in implementing shopping cart

我是 JS 新手,我正在做一个项目,我需要使用 JavaScript 实现一个简单的购物车。

我使用 PHP 从数据库中获取产品并使用以下代码显示它们:

<div class="col-lg-10 item">
            <?php
            $return = $dbObject ->getProduce('fruits', 3);

            foreach( $return as $key =>$row){
                $id = $row['produce_id'];
                $stock = $row['produce_available'];
                $name = $row['produce_name'];
                $unit = $row['produce_unit'];
                $price = $row['produce_unit_price'];
                $imgName = $row['produce_image_name'];
                $imgFolder = $row['produce_image_folder'];

                ?>

                <script>
                    var key = itemKey();
                </script>

                    <div class='col-lg-4 col-sm-6 col-md-4' >
                        <div class='thumbnail'>
                            <p style='visibility : ' id = 'itemId'><?php echo $id; ?></p>
                            <p style='visibility : hidden' id = 'itemStock'><?php echo $stock; ?></p>
                            <p class='text-center' id = "itemName"><?php echo $name; ?></p>
                            <img src='admin/<?php echo $imgFolder ."/".$imgName; ?>'>
                            <div class='caption'>
                                <p>kshs. <span id = 'itemPrice'><?php echo $price; ?> </span> /= per <span id = 'itemUnit'><?php echo $unit; ?></span>
                                <button class='btn pull-right' class = 'cartBtn' id = '' onclick = 'display(addToCart(key))'><span class='glyphicon glyphicon-shopping-cart'></span></button></p>
                            </div>
                        </div>
                    </div>


                <?php
            }
            ?>

        </div>

这是单击“添加到购物车”按钮时应执行的 JS 代码:

var cart = [];

        function addToCart(item){
            var id = $("#itemId").text();
            var name = $("#itemName").text();
            var stock = $("#itemStock").text();
            var unit = $("#itemUnit").text();
            var price = $("#itemPrice").text();


                var cartItem = {
                    cartItemId : id,
                    cartItemName : name,
                    cartItemStock : stock,
                    cartItemUnit : unit,
                    cartItemPrice : price,
                }

                cart.push(cartItem);
                console.log(cart);
                return cart;
            }

        function itemKey(){
            var key;
            key = Math.floor(Math.random() * 10000000001);
            return key;
        }


        function checkIfInCart(item){
            //check if item is in cart
            var inCart = false;
            if(cart.includes(item) == true){
                inCart = true;
            }
            else{
                incart = false;
            }

        return inCart;
        }


        function display(){
            for(i = 0; i < cart.length; i ++){
                $("#cartContents").html("<tr><td></td><td>" + cart[i].cartItemName + "</td><td></td><td>" + cart[i].cartItemPrice + "</td><td></td></tr>");
            }
        }

它工作正常,除了数组只接受一个项目,如果您单击按钮将另一个项目 push() 到购物车数组,它只会复制购物车中已有的第一个项目。 输出的 console.log 如下所示:

 (1) […]
​
0: Object { cartItemId: "4", cartItemName: "Apples", cartItemStock: "200", … }
​
length: 1
​
<prototype>: Array []

​
0: Object { cartItemId: "4", cartItemName: "Apples", cartItemStock: "200", … }
​
1: Object { cartItemId: "4", cartItemName: "Apples", cartItemStock: "200", … }
​
length: 2
​
<prototype>: Array []

(3) […]
​
0: Object { cartItemId: "4", cartItemName: "Apples", cartItemStock: "200", … }
​
1: Object { cartItemId: "4", cartItemName: "Apples", cartItemStock: "200", … }
​
2: Object { cartItemId: "4", cartItemName: "Apples", cartItemStock: "200", … }
​
length: 3

我怎样才能确保购物车接受第二个和第三个......添加的项目而不是复制第一个?

TL;DR:PHP 中的 foreach 循环会将多个#itemId元素渲染到 DOM 中,并且您总是在查询第一个元素


您没有在addToCart(item)使用item参数,也没有将其设置为代表特定项目的唯一值:

...
var key = itemKey(); // this always generates a unique value, it doesn't point to the current $row item rendered in the PHP context
...
onclick = 'display(addToCart(key))' // here you are just passing that random value to the add function
...

在函数本身中,您正在查询 DOM 中与 ID 匹配的第一个项目(始终是第一个),而不是特定项目的 dom 元素:

...
function addToCart(item){
            var id = $("#itemId").text(); // this will always choose the first #itemId element in DOM
            var name = $("#itemName").text();
            var stock = $("#itemStock").text();
            var unit = $("#itemUnit").text();
            var price = $("#itemPrice").text();
...

有多种方法可以解决这个问题,更简单的方法是将另一个唯一标识符(每个产品)添加到 dom 中,以便您可以选择特定产品的名称(和其他属性):

<div class='thumbnail' id='product-<?php echo $id; ?>'> // added a per-product DOM element ID #product-X

然后你需要在点击处理程序中传递它:

...
onclick = 'display(addToCart("#product-<?php echo $id; ?>"))' // passing that id to the add function
...

现在您可以像这样更改查询:

...
function addToCart(item){
            var id = $(item + " #itemId").text(); // now the query will find the correct element
            var name = $(item + " #itemName").text();
            var stock = $(item + " #itemStock").text();
            var unit = $(item + " #itemUnit").text();
            var price = $(item + " #itemPrice").text();
...

另请注意,在一个页面上多次使用相同的元素 ID 并不完全干净,我建议改用类。

您可以使用以下代码在数组中提供唯一元素,这将避免重复元素的问题

` //过滤唯一值 const array = [1, 1, 2, 3, 5, 5, 1];

const uniqueArray = [...new Set(array)];

console.log(uniqueArray);`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM