簡體   English   中英

使用JavaScript Cookie的簡單購物車

[英]Simple shopping cart using JavaScript Cookie

我有以下代碼使用JavaScript實現簡單的練習購物車。 有一個結賬鏈接,調用getcookie()來檢查存儲的cookie的值。 如果cookie中沒有任何內容,則單擊鏈接警報以進行輸入。 如果在輸入框中輸入了非值並點擊“添加到購物車”,則完成驗證並提醒錯誤消息。

由於某種原因,cookie沒有從輸入字段中獲取值。 我現在嘗試了一段時間,但無法調試代碼。 最后只顯示一個空警報框。 我很感激任何調試。 提前致謝。

<script type="text/javascript">
    var value;
    var productID;

    function setItem(abd) {
        value = abd.value;
        productID = abd.getAttribute("productID");
        var intRegex = /^\d+$/;
        var numberOfItems;
        if (!intRegex.test(value) || (value <= 0)) {
            alert('Please Enter valid numberofitem');
        } else {
            numberOfItems = value;
        }
    }
    function getCookie() {
        if (value == undefined) {
            alert("There is nothing in the shopping cart!");
        } else {
            var cookieArray = document.cookie.split(';');
            var printHolder = "";
            for (var i = 0; i < cookieArray.length; ++i) {
                var pairArray = cookieArray[i].split('=');
                alert(pairArray[0]);
            }
            alert(printHolder);
        }
    }
    function setCookie() {
        if (value == undefined) {
            alert("Please add number of items in text box");
        } else {
            document.cookie = productID + "=" + value + "; ";
            alert(value + " Product(s) with id " + productID +
                " has been added to shopping cart!");
        }
    }

</script>
<a href="javascript:getCookie()"> Checkout </a>
<input name="item-select" id="item-select"
       productid="p001"  style="width: 50px" onBlur="setItem(this)" >
<button type="button" onclick="setCookie()">Add to cart.</button>

我想要的結果就是這樣的結果!

在此輸入圖像描述

這段代碼完美地適用於一些變化。 我正在使用chrome,后來發現了這一點

當文件位於local machine並使用文件路徑直接加載到瀏覽器中時,Google Chrome不會創建Cookie。

而是嘗試使用localhost. 當您將代碼放入服務器時,它肯定會起作用。 Chrome在這里變得很痛苦!

如果你想用Javascript創建購物車,請點擊此鏈接。 http://www.smashingmagazine.com/2014/02/create-client-side-shopping-cart/

你的getCookie可能會給你不正確的結果。

var cookiearray= document.cookie.split(';');
var toprint="";
for(var i=0; i<cookiearray.length; ++i) 
{ 
    var pairArray= cookiearray[i].split('=');
    alert(pairArray[0]);
}
alert(toprint);

這里有兩件事不對;

1)當你處於for循環中時,每次循環時,你都會一直警告數組中的第一項pairArray [0]你需要將它改為pairArray [i]

2)您顯示為空警報,因為這是您分配給toprint變量的內容。 - 您在for循環之前為頂部分配了一個空字符串然后您在不為其賦值的情況下警告該變量 ,因此您將顯示一個空的警告框! - 還要確保您的cookie數組不為空

嘗試一下,享受編碼:)

庫什

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM