Home Web Front-end JS Tutorial Use native JavaScript to implement shopping carts and shopping pages

Use native JavaScript to implement shopping carts and shopping pages

Aug 22, 2017 pm 05:08 PM
javascript js shopping cart

The following editor will bring you an article on how to use cookies for native JS shopping carts and shopping pages. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Go directly to the code:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物页面</title>
<style>
ul{list-style:none;padding:0;margin:0;}
.goods li{display:inline-block;border:1px solid #ddd;padding:10px;margin:10px;}
.goods li:hover{}
.goods .price{color:#f00;font-weight:bold;}
.goods .price::before{
content:"¥";
}
</style>
<script>
window.onload = function(){
var goods = document.getElementsByClassName(&#39;goods&#39;)[0];

// 用于保存购物车商品信息
var carList = [];

// 先获取当前cookie
var cookies = document.cookie.split(&#39;; &#39;);
for(var i=0;i<cookies.length;i++){
var arr = cookies[i].split(&#39;=&#39;);
if(arr[0] === &#39;carlist&#39;){
carList = JSON.parse(arr[1]);
}
}

// 事件委托
goods.onclick = function(e){
e = e || window.event;
var target = e.target || e.srcElement;

// 添加到购物车
if(target.tagName.toLowerCase() === &#39;button&#39;){

// 获取当前li
var currentLi = target.parentElement.parentElement;
var children = currentLi.children;
var currentGUID = currentLi.getAttribute(&#39;data-guid&#39;);

// 先创建一个对象保存当前商品信息
var goodsObj = {};
goodsObj.guid = currentGUID;
goodsObj.qty = 1;
goodsObj.name = children[1].innerHTML;
goodsObj.price = children[2].innerHTML;
goodsObj.imgUrl = children[0].src;

// 如果cookie为空,则直接添加
if(carList.length===0){
// 添加到carList
carList.push(goodsObj);
}else{
// 先判断cookie中有无相同的guid商品
for(var i=0;i<carList.length;i++){
// 如果商品已经存在cookie中,则数量+1
if(carList[i].guid === currentGUID){
carList[i].qty++;
break;
}
}

// 如果原cookie中没有当前商品
if(i===carList.length){
// 添加到carList
carList.push(goodsObj);
}

}	
// 存入cookie
// 把对象/数组转换诚json字符串:JSON.stringify()
document.cookie = &#39;carlist=&#39; + JSON.stringify(carList);
}

}
}
</script>
</head>
<body>
<ul class="goods">
<li data-guid="g01">
<img src="images/shirt_1.jpg">
<p>短袖衬衣</p>
<p class="price">98.88</p>
<p class="add2cart">
<button>添加到购物车</button>
</p>
</li>
<li data-guid="g02">
<img src="images/shirt_2.jpg">
<p>短袖衬衣2</p>
<p class="price">88.88</p>
<p class="add2cart">
<button>添加到购物车</button>
</p>
</li>
<li data-guid="g03">
<img src="images/shirt_3.jpg">
<p>短袖衬衣3</p>
<p class="price">9.98</p>
<p class="add2cart">
<button>添加到购物车</button>
</p>
</li>
<li data-guid="g04">
<img src="images/shirt_4.jpg">
<p>短袖衬衣4</p>
<p class="price">8.88</p>
<p class="add2cart">
<button>添加到购物车</button>
</p>
</li>
</ul>
<a href="04car.html" rel="external nofollow" >去结算</a>
</body>
</html>
Copy after login

//Shopping cart page


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车</title>
<style>
#carList li{position:relative;padding-bottom:15px;margin-bottom:15px;border-bottom:1px solid #ddd;}
#carList img{display:block;width:100px;}
#carList li .btn-close{position:absolute;top:0;right:0;padding:0 5px;cursor:default;}
#carList li .btn-close:hover{color:#fff;}
.subPrice{padding:5px 20px;color:#f00;font-weight:bold;text-align:right;}
#carList .price{color:#f00;}
.price::before{
content:&#39;¥&#39;;
font-size:11px;
}
#carList .price span{font-size:11px;}
</style>
<script>
window.onload = function(){
/*
读取cookie中的carlist
把json字符串转换成对象/数组:JSON.parse()
json字符串格式:
1.必须用双引号
2.不能右注释
*/
var oCarList = document.getElementById(&#39;carList&#39;);
var oSubPrice = oCarList.nextElementSibling;
var btnClear = document.getElementById(&#39;btnClear&#39;);

var carList;
var cookies = document.cookie.split(&#39;; &#39;);
for(var i=0;i<cookies.length;i++){
var arr = cookies[i].split(&#39;=&#39;);
if(arr[0] === &#39;carlist&#39;){
console.log(JSON.parse(arr[1]));
carList = JSON.parse(arr[1]);
}
}

var subPrice = 0;

if(carList){
var ul = document.createElement(&#39;ul&#39;);
for(var i=0;i<carList.length;i++){
var li = document.createElement(&#39;li&#39;);
// 给每个li添加data-guid属性
li.setAttribute(&#39;data-guid&#39;,carList[i].guid);

// 商品名
var title = document.createElement(&#39;h4&#39;);
title.innerHTML = carList[i].name;

// 商品价格
var price = document.createElement(&#39;p&#39;);
price.className = &#39;price&#39;;
price.innerHTML = carList[i].price + &#39;×&#39; + carList[i].qty;

// 商品图片
var img = document.createElement(&#39;img&#39;);
img.src = carList[i].imgUrl;

// 添加删除按钮
var btnClose = document.createElement(&#39;span&#39;);
btnClose.innerHTML = &#39;×&#39;;
btnClose.className = &#39;btn-close&#39;;

// 计算总价
subPrice += carList[i].price*carList[i].qty;

li.appendChild(title);
li.appendChild(price);
li.appendChild(img);
li.appendChild(btnClose);

ul.appendChild(li);
}

// 写入页面
oCarList.appendChild(ul);

// 写入总价
// toFixed(n)获取小数点后n位(自动四舍五入,Number类型的方法)
oSubPrice.innerHTML = &#39;<span class="price">&#39; + subPrice.toFixed(2) + &#39;</span>&#39;;
}


// 删除商品
oCarList.onclick = function(e){
e = e || window.event;
var target = e.target || e.srcElement;

// 是否点击了删除按钮
if(target.className === &#39;btn-close&#39;){
var currentLi = target.parentElement;

// 获取当前guid
var currentGUID = currentLi.getAttribute(&#39;data-guid&#39;);

// 删除cookie中对应的商品
// 根据guid取对比
for(var i=0;i<carList.length;i++){
// 找出要删除的商品
if(carList[i].guid === currentGUID){
carList.splice(i,1);
break;
}
}

// 更新cookie
document.cookie = &#39;carlist=&#39; + JSON.stringify(carList);

// 删除li节点
currentLi.parentElement.removeChild(currentLi);
}
}

// 清空购物车
// 1、删除DOM节点
// 2、删除cookie
btnClear.onclick = function(){
oCarList.innerHTML = &#39;&#39;;
oSubPrice.innerHTML = &#39;&#39;;

// 利用设置有效期位过期事件来达到删除cookie的效果
var now = new Date();
now.setDate(now.getDate()-7);
document.cookie = &#39;carlist=xx;expires=&#39; + now;
}
}

</script>
</head>
<body>
<h1>购物车</h1>
<p id="carList">

</p>
<p class="subPrice"></p>
<a href="#" rel="external nofollow" id="btnClear">清空购物车</a>
</body>
</html>
Copy after login

The above is the detailed content of Use native JavaScript to implement shopping carts and shopping pages. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1652
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Practical tutorial: Detailed explanation of shopping cart function with PHP and MySQL Practical tutorial: Detailed explanation of shopping cart function with PHP and MySQL Mar 15, 2024 pm 12:27 PM

Practical tutorial: Detailed explanation of the shopping cart function with PHP and MySQL. The shopping cart function is one of the common functions in website development. Through the shopping cart, users can easily add the goods they want to buy to the shopping cart, and then proceed with settlement and payment. In this article, we will detail how to implement a simple shopping cart function using PHP and MySQL and provide specific code examples. To create a database and data table, you first need to create a data table in the MySQL database to store product information. The following is a simple data table

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles