JavaScript Shopping Cart Implementation detailed code explanation

Source: Internet
Author: User

We are sure that we are familiar with the function of shopping cart, whenever we buy goods in a certain treasure on the east of the time, fancy which item, will join the shopping cart, the final settlement. The shopping cart This function, the convenience consumer to manage the commodity, may add the commodity, deletes the commodity, selects one item or several items in the shopping cart, the final commodity price also can with the consumer's operation along with the change.
Now, the author of the shopping Cart for a simple implementation, to achieve the real shopping cart most of the functions. In this example, the use of JavaScript in the BOM operations, DOM operations, table operations, Cookie,json and other knowledge points, at the same time, the use of three-tier architecture for shopping cart design, the integrated application of JavaScript is strong, There is a certain benefit to the JavaScript beginner's advanced step.
See home effects:

Now that readers have an idea of the home page, I enclose the HTML code for the homepage for readers ' reference and suggest that the reader write the code according to their own ideas. See HTML code:

<! DOCTYPE html>  

After the HTML structure code is available, you can design the CSS for the home page, which does not explain the CSS too much.
Once we have designed the home page, we can do DOM operations related to the homepage, involving the Click event to add buttons, cookies, and JSON applications, cookies are intended to be used to share the current data with the shopping cart for ease of operation. See the JavaScript code associated with it:
This is index.js code, mainly related to the home page:

/* Thinking: First step: Get the Node object to operate the second step: when the page is loaded, you need to calculate how many local cookies stored "" "merchandise, the number assigned to Ccount third step: For each item corresponding to the Add Cart button to bind a 
            Click on the event onclick change local cookies get the current product PID Loop traverse the local cookie converted array, take out each object's PID contrast, if equal, the product is not the first time to add Remove the item from the shopping cart and add a pcount value of 1 Otherwise: Create a new object and save it to the shopping. At the same time the quantity of the product is 1/var ccount = document.getElementById ("Ccount"); The Label node object that displays the total quantity of merchandise var btns = Document.queryselectorall (". List DL dd button");
All cart buttons//Conventions use a cookie named Datas to store the data information in the cart datas is a JSON string var liststr = Cookieobj.get ("Datas"); * To determine whether there is a local shopping cart (datas), if not, create an empty shopping cart, some words directly to use * */if (!LISTSTR) {//No shopping cart datas json cookieobj.set ({nam
    E: "Datas", Value: "[]"});
Liststr = Cookieobj.get ("Datas"); var listobj = Json.parse (LISTSTR); The array/* loop iterates through the array to get the sum of the pcount values in each of the objects (= $ totalcount = 0); The default is 0 for (var i = 0, len = listobj.length i < len; i++) {totalcount = Listobj[i].pcount + totalcount;} ccount.i nnerhtml = TotalCount;

/* Loop Add click event for each button/for (var i = 0, len = btns.length i < len; i++) {Btns[i].onclick = function () {var d
        L = This.parentNode.parentNode;
            var pid = Dl.getattribute ("pid")//Get custom attribute var arrs = dl.children;//Get all child nodes if (Checkobjbypid (PID)) {
            Listobj = Updateobjbyid (PID, 1)} else {var imgsrc = arrs[0].firstelementchild.src;
            var pname = arrs[1].innerhtml;
            var pdesc = arrs[2].innerhtml;
            var price = arrs[3].firstelementchild.innerhtml; var obj = {pid:pid, pimg:imgsrc, Pname:pname, pdesc:p
            Desc, Price:price, pcount:1};
        Listobj.push (obj) listobj = UpdateData (listobj);
    } ccount.innerhtml = Gettotalcount (); }
}

This is the Cookie.js code, mainly related to the cookies set up to get operations, using a single example design mode for the encapsulation design, see Code:

/* Single example design pattern complete form: [] is optional document.cookie = "name=value[;expires=date][;p ath=path-to-resource][;d omain= domain name][;SECU RE] "*/var cookieobj = {/* Add or modify cookie parameters: O Object {} name:string cookie name value:string C  Ookie value expires:date Object expiration path:string path limit domain:string domain name limit secure:boolean true HTTPS False or Undeinfed */set:function (o) {var cookiestr = encodeURIComponent (o.name) + "=" + Encodeuricompon
        ENT (O.value);
        if (o.expires) {cookiestr + = "expires=" + o.expires;
        } if (O.path) {cookiestr + = ";p ath=" + o.path;
        } if (O.domain) {cookiestr + = ";d omain=" + o.domain;
        } if (o.secure) {cookiestr = = "; secure";
    } document.cookie = cookiestr;
        },/* Delete parameter: N string cookie's name/del:function (n) {var date = new Date ();
        Date.sethours (-1);This represents the object This.set ({name:n, expires:date}) of the current function;
        },/* Find/* Get:function (n) {n = encodeuricomponent (n);
        var cooiketotal = Document.cookie;
        var cookies = Cooiketotal.split (";");
            for (var i = 0, len = cookies.length i < len; i++) {var arr = cookies[i].split ("=");
            if (n = = Arr[0]) {return decodeuricomponent (arr[1]); }
        }
    }
}

The following is the Server.js code, the main shopping cart in a variety of operations are packaged, such as the number of merchandise statistics, update access to local data and other operations, convenient code management, see Code:

/* Function: To see if the local data contains the specified object (commodity), according to the ID parameter: ID: Product Identification/function Checkobjbypid (ID) {var jsonstr = cookieobj.get ("Data
    S ");
    var jsonobj = Json.parse (JSONSTR);
    var isexist = false;
            for (var i = 0, len = jsonobj.length i < len; i++) {if (jsonobj[i].pid = = id) {isexist = true;
        Break } return isexist;
return false; /* Function: Update local data parameters: Arr Array object Returns a value: the newest locally converted array Object */function UpdateData (arr) {var jsonstr = Json.str
    Ingify (arr);
    Cookieobj.set ({name: "Datas", value:jsonstr});
    Jsonstr = Cookieobj.get ("Datas");
Return Json.parse (JSONSTR); /* Get total quantity of merchandise returned: Digital/function Gettotalcount () {/* loop traversal array, get the sum of pcount values in each of the objects * * var totalcount = 0;
    The default is 0 var jsonstr = cookieobj.get ("Datas");
    var listobj = Json.parse (JSONSTR);
    for (var i = 0, len = listobj.length i < len; i++) {totalcount = Listobj[i].pcount + totalcount; } return TotalCount;
    /* Update local data based on PID ID: Product ID/function Updateobjbyid (ID, num) {var jsonstr = Cookieobj.get ("Datas");
    var listobj = Json.parse (JSONSTR);  for (var i = 0, len = listobj.length i < len; i++) {if (listobj[i].pid = = id) {Listobj[i].pcount =
            Listobj[i].pcount + num;
        Break } return UpdateData (Listobj)}/* Get Local Data returns array Object * */function Getalldata () {var jsonstr = cookie
    Obj.get ("Datas");
    var listobj = Json.parse (JSONSTR);
return listobj;
    function Deleteobjbypid (id) {var lisobj = Getalldata ();
            for (var i = 0, len = lisobj.length i < len; i++) {if (lisobj[i].pid = = ID) {Lisobj.splice (I, 1);
        Break
    } updatedata (Lisobj);
return lisobj; }

Because the above code involved some of the operations after entering the shopping cart, the reader may be moved to doubt after reading, do not worry, please look at the following click into my shopping cart analysis.
See the effect map:

The author clicks on the home Page three items, a total of seven clicks, in the shopping cart appeared in the corresponding commodity and price calculation. For all kinds of information on the way, I believe that readers at a glance. Please look at the HTML code for this shopping cart:

<! 
        DOCTYPE html> 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.