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: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version