简体   繁体   English

JS Array 实现购物车的问题

[英]JS Array problem in implementing shopping cart

I am new to JS and i'm working on a project where I need to implement a simple shopping cart using JavaScript.我是 JS 新手,我正在做一个项目,我需要使用 JavaScript 实现一个简单的购物车。

Im fetching the products from the database using PHP and displaying them using this code:我使用 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>

This is the JS code that should be executed when the 'Add to Cart' Button is clicked:这是单击“添加到购物车”按钮时应执行的 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>");
            }
        }

It works fine, except that the array only accepts only one item and the if you click the button to push() another item to the cart array, it only duplicates the first item already in the cart.它工作正常,除了数组只接受一个项目,如果您单击按钮将另一个项目 push() 到购物车数组,它只会复制购物车中已有的第一个项目。 The console.log for the output looks like this:输出的 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

How can I ensure that the Cart accepts a second and third.... items added instead of duplicating the first?我怎样才能确保购物车接受第二个和第三个......添加的项目而不是复制第一个?

TL;DR: the foreach loop in PHP will render multiple #itemId elements into DOM and you are querying always for the first one TL;DR:PHP 中的 foreach 循环会将多个#itemId元素渲染到 DOM 中,并且您总是在查询第一个元素


You are not using the item argument in addToCart(item) nor you are setting it to a unique value that would represent a specific item:您没有在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
...

And in the function itself you are querying for the first item in the DOM that matches the ID (always the first one) instead of a specific item's dom element:在函数本身中,您正在查询 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();
...

There are multiple ways to solve it the easier one being to add another unique identifier (per product) into the dom so you can select name (and the other properties) of a specific product:有多种方法可以解决这个问题,更简单的方法是将另一个唯一标识符(每个产品)添加到 dom 中,以便您可以选择特定产品的名称(和其他属性):

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

Then you need to pass that it in the click handler:然后你需要在点击处理程序中传递它:

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

Now you can change your queries like so:现在您可以像这样更改查询:

...
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();
...

Also please note that it is not exactly clean to have the same element ID multiple times on one page and I would recommend to use classes instead.另请注意,在一个页面上多次使用相同的元素 ID 并不完全干净,我建议改用类。

You can use below code which gives unique elements in an array, This will avoid the problem of duplicate elements您可以使用以下代码在数组中提供唯一元素,这将避免重复元素的问题

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

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

console.log(uniqueArray);` console.log(uniqueArray);`

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

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