search
HomeWeb Front-endJS TutorialDetailed explanation of steps to implement shopping cart function using JS

This time I will give you a detailed explanation of the steps to use JS to implement the shopping cart function. What are the precautions for using JS to implement the shopping cart function. The following is a practical case, let’s take a look.

We must all be familiar with the function of the product shopping cart. Whenever we purchase products on a certain website, which product we like, we will add it to the shopping cart and finally settle. The shopping cart function facilitates consumers to manage products. They can add products, delete products, select one or several products in the shopping cart, and the final total price of the products will also change with the consumer's operations.

Now, the author has made a simple implementation of the shopping cart, which can realize most of the functions of the real shopping cart. In this example, BOM operations, DOM operations, table operations, cookies, json and other knowledge points in JavaScript are used. At the same time, a three-layer architecture is used to design the shopping cart, which has strong comprehensive application of JavaScript and is suitable for beginners of JavaScript. There are certain benefits to advancing.

Please take a look at the renderings of the homepage:

Now that readers have understood the renderings of the homepage, I am attaching the html code of the homepage here for your reference. For readers' reference, it is recommended that readers write code according to their own ideas.

Please look at the html code:

nbsp;html>

 
 <meta>
 <title>商品列表页面</title>
 <!--商品列表样式表-->
 <link>
 <!--cookie操作的js库-->
 <script></script>
 
 
 <p>
  </p><h1 id="商品列表">商品列表</h1>
  <p>
  <a>我的购物车</a><i>0</i>
  </p>
  <p>
  </p>
   
   Detailed explanation of steps to implement shopping cart function using JS    
   
智能手表
   
酷黑,棒,棒,棒,棒
   
998
   
       
  
  
   
   Detailed explanation of steps to implement shopping cart function using JS    
   
智能手机001
   
金红色,酷酷酷酷
   
1998
   
       
  
  
   
   Detailed explanation of steps to implement shopping cart function using JS    
   
华为手机002
   
帅帅帅帅帅帅帅帅帅帅
   
998
   
       
  
  
   
   Detailed explanation of steps to implement shopping cart function using JS    
   
华为手机003
   
杠杠的
   
2000
   
       
  
        <script></script>    <script></script>  

After the html structure code is available, you can perform CSS performance design on the homepage. I will not explain too much about CSS here.

After we design the homepage, we can perform DOM operations related to the homepage, including adding button click events, cookie and json applications. Cookies are mainly used to share current data with the shopping cart. Easy to operate. Please look at the related javascript code:

This is the index.js code, mainly related to the homepage operations:

/*
 思路:
 第一步:获取所要操作的节点对象
 第二步:当页面加载完后,需要计算本地cookie存了多少【个】商品,把个数赋值给ccount
 第三步:为每一个商品对应的添加购物车按钮绑定一个点击事件onclick
  更改本地的cookie
  获取当前商品的pid
  循环遍历本地的cookie转换后的数组,取出每一个对象的pid进行对比,若相等则该商品不是第一次添加
  从购物车中取出该商品,然后更pCount值追加1
  否则:创建一个新的对象,保存到购物中。同时该商品的数量为1
 */
var ccount = document.getElementById("ccount"); //显示商品总数量的标签节点对象
var btns = document.querySelectorAll(".list dl dd button"); //所有的购物车按钮
//约定好用名称为datas的cookie来存放购物车里的数据信息 datas里所存放的就是一个json字符串
var listStr = cookieObj.get("datas");
/*判断一下本地是否有一个购物车(datas),没有的话,创建一个空的购物车,有的话就直接拿来使用*/
if(!listStr) { //没有购物车 datas json
 cookieObj.set({
 name: "datas",
 value: "[]"
 });
 listStr = cookieObj.get("datas");
}
var listObj = JSON.parse(listStr); //数组
/*循环遍历数组,获取每一个对象中的pCount值相加总和*/
var totalCount = 0; //默认为0
for(var i = 0, len = listObj.length; i <p style="text-align: left;">This is the cookie.js code, mainly related to cookie settings and acquisition The operation is encapsulated using the singleton <a href="http://www.php.cn/course/58.html" target="_blank"> design pattern </a>. Please see the code: </p><pre class="brush:php;toolbar:false">/*
 单例设计模式
 完整形式:[]中是可选项
 document.cookie = “name=value[;expires=date][;path=path-to-resource][;domain=域名][;secure]”
*/
var cookieObj = {
 /*
 增加或修改cookie
 参数:o 对象{}
 name:string cookie名
 value:string cookie值
 expires:Date对象 过期时间
 path:string 路径限制
 domain:string 域名限制
 secure:boolean true https false或undeinfed 
 */
 set: function(o) {
 var cookieStr = encodeURIComponent(o.name) + "=" + encodeURIComponent(o.value);
 if(o.expires) {
  cookieStr += ";expires=" + o.expires;
 }
 if(o.path) {
  cookieStr += ";path=" + o.path;
 }
 if(o.domain) {
  cookieStr += ";domain=" + o.domain;
 }
 if(o.secure) {
  cookieStr += ";secure";
 }
 document.cookie = cookieStr;
 },
 /*
 删除
 参数:n string cookie的名字
 */
 del: function(n) {
 var date = new Date();
 date.setHours(-1);
 //this代表的是当前函数的对象
 this.set({
  name: n,
  expires: date
 });
 },
 /*查找*/
 get: function(n) {
 n = encodeURIComponent(n);
 var cooikeTotal = document.cookie;
 var cookies = cooikeTotal.split("; ");
 for(var i = 0, len = cookies.length; i <p style="text-align: left;"> The following is the server.js code, which mainly encapsulates various operations in the shopping cart, such as Count the number of products, update and obtain local data, and other operations to facilitate code management. Please see the code: </p><pre class="brush:php;toolbar:false">/*
 功能:查看本地数据中是否含有指定的对象(商品),根据id
 参数:id:商品的标识
 */
function checkObjByPid(id) {
 var jsonStr = cookieObj.get("datas");
 var jsonObj = JSON.parse(jsonStr);
 var isExist = false;
 for(var i = 0, len = jsonObj.length; i <p style="text-align: left;"> Because the above code involves some operations after entering the shopping cart, readers may be confused after reading it. Don’t worry, please see the analysis after clicking to enter my shopping cart below. </p><p style="text-align: left;">Please see the rendering: </p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/8bff5f68d03d360912871c55ab58e1a3-1.png?x-oss-process=image/resize,p_40" class="lazy" id="theimg" alt=""></p><p   style="max-width:90%">The author clicked on three products on the homepage, a total of seven times, and the corresponding products appeared in the shopping cart and price calculations. I believe readers can understand all kinds of information along the way at a glance. Please look at the html code of this shopping cart: </p><pre class="brush:php;toolbar:false">nbsp;html>

 
 <meta>
 <title>购物车</title>
 <!--购物车样式表-->
 <link>
 <!--操作cookie的js文件-->
 <script></script>
 
 
 <p>
  </p><h1 id="购物车">购物车</h1>
  <h3 id="a-返回商品列表页面-a"><a>返回商品列表页面</a></h3>
  
                                                      
    全选         图片         描述         数量         单价         小计         操作    
  

购物车里没有任何商品

  

总价格:¥0

   <script></script>    <script></script>  

After designing the relevant performance of the shopping cart, we need to design the javascript behavior. Please look at the cart.js code related to this page:

/*
 思路:
 第一步:当页面加载完后,根据本地的数据,动态生成表格(购物车列表)
  获取所要操作的节点对象
  判断购物车中是否有数据?
  有:
   显示出购物列表
  没有:
   提示购物车为空
 第二步:当购物车列表动态生成后,获取tbody里所有 的checkeBox标签节点对象,看那个被选中就获取对应行小计进行总价格运算。
 第三步:
  为每一个checkbox添加一个onchange事件,根据操作更改总价格
 第四步:全选
 第五步:
  为加减按钮添加一个鼠标点击事件
  更改该商品的数量
 第六步:删除
  获取所有的删除按钮
  为删除按钮添加一个鼠标点击事件
  删除当前行,并更新本地数据
 */
var listObj = getAllData();
var table = document.getElementById("table")
var box = document.getElementById("box")
var tbody = document.getElementById("tbody");
var totalPrice = document.getElementById("totalPrice");
var allCheck = document.getElementById("allCheck");
if(listObj.length == 0) { //购物车为空
 box.className = "box";
 table.className = "hide";
} else {
 box.className = "box hide";
 table.className = "";
 for(var i = 0, len = listObj.length; i ' +
  '<input>' +
  '' +
  '<td>' +
  '<img  src="/static/imghwm/default1.png" data-src="' + listObj[i].pImg + '" class="lazy" alt="Detailed explanation of steps to implement shopping cart function using JS" >' +
  '</td>' +
  '<td>' +
  listObj[i].pDesc +
  '</td>' +
  '<td>' +
  '<button>-</button><input><button>+</button>' +
  '</td>' +
  '<td>' +
  '¥<span>' + listObj[i].price + '</span>' +
  '</td>' +
  '<td>' +
  '¥<span>' + listObj[i].price * listObj[i].pCount + '</span>' +
  '</td>' +
  '<td>' +
  '<button>删除</button>' +
  '</td>';
 tbody.appendChild(tr);
 }
}
/*
 功能:计算总价格
 */
var cks = document.querySelectorAll("tbody .ck");
function getTotalPrice() {
 cks = document.querySelectorAll("tbody .ck");
 var sum = 0;
 for(var i = 0, len = cks.length; i  <p style="text-align: left;">The above code completes the relevant operations in the shopping cart, such as price calculation, product quantity replacement, <a href="http://www.php.cn/code/6807.html" target="_blank">product deletion</a> and other operations. </p><p style="text-align: left;">At this point we have completed most of the functions of the shopping cart. We have comprehensively applied html, css, BOM, DOM, json, cookie, etc. I believe that readers will learn more about their own javascript after understanding it. Furthermore, most of the code involved in this example is posted on this page, and some code resources are not shown to readers. Readers can click on the resource link below to download all the code and picture materials of this example. This example is compiled and run using the HBuilder compiler and involves cookie operations. Readers are asked to install the server themselves or add it to HBuilder to run and view. </p><p style="text-align: left;">Resource link: Download all resources in the shopping cart</p><p>I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website! </p><p>Recommended reading: </p><p style="text-align: left;"><a href="http://www.php.cn/php-weizijiaocheng-396091.html" target="_blank">php curl batch control concurrent asynchronous operations</a><br></p><p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-396088.html" target="_blank">PHP quick implementation of array deduplication method</a> <br></p>

The above is the detailed content of Detailed explanation of steps to implement shopping cart function using JS. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.