使用 JavaScript Cookie 的简单购物车

Din*_*ota 1 html javascript cookies shopping-cart setcookie

我有以下代码来使用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>
Run Code Online (Sandbox Code Playgroud)

我想要的结果最后是这样的!

在此输入图像描述

Din*_*ota 5

这段代码经过一些更改后可以完美运行。 我用的是chrome,后来发现

当文件位于local machine并直接使用文件路径加载到浏览器中时,Google Chrome 不会创建 cookie。

而是尝试使用localhost.当您将代码放入服务器时它肯定可以工作。Chrome在这里变得很痛苦!

如果您想了解使用 Javascript 创建购物车的想法,请点击此链接。 http://www.smashingmagazine.com/2014/02/create-client-side-shopping-cart/