簡體   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