search
HomeWeb Front-endJS TutorialHow to implement the shopping cart function in javascript (code)

The content of this article is about how to implement the shopping cart function (code) in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

nbsp;html>


    <meta>
    <title>购物车</title>
    <style>
        table{
            width: 600px;
            margin: 0 auto;
            border-collapse: collapse;
        }
        td{
            border: 1px solid silver;
            line-height: 40px;
            text-align: center;
        }
        .btnl,.btnr{
            border-style: none;
            outline: none;
            color: deeppink;
        }
        .txt{
            width: 30px;
            height: 30px;
            border-style: none;
            outline: none;
            text-align: center;
        }
    </style>


                                                                                                                                                                                                                                                                                                                                                                                                        
序号名称价钱数量小计操作
1毛衣 99 99
2短袖 108 108
3运动鞋 10000 10000
4凉鞋 25 25
总计:0
<script> //获取左右的按钮集合 var btnleft=document.getElementsByClassName("btnl"); var btnright=document.getElementsByClassName("btnr"); //获取表示数量的class名为txt的input元素集合 var txt=document.getElementsByClassName("txt"); //获取表示单价的class名为price的span元素集合 var price=document.getElementsByClassName("price"); //获取表示小计的class名为smallprice的span元素集合 var small=document.getElementsByClassName("smallprice"); //获取表示总价的class名为totle的span元素 var totle=document.getElementsByClassName("totle")[0]; //获取全选反选按钮和选择框 var btna=document.getElementById("btna"); var btnf=document.getElementById("btnf"); var box=document.getElementsByClassName("ckbox"); //获取删除按钮 var btndelete=document.getElementsByClassName("btndelete"); var trlist=document.getElementsByClassName("trinfo"); var totleprice=0; //定义全局变量totleprice的初值为0 //给数量左右两边的+-添加点击事件 for(var i=0;i<btnleft.length;i++) { btnleft[i].index=i; //把i的值赋给btnleft[i]的index btnleft[i].onclick=function (){ //获取当前对应的文本框的值 var val=txt[this.index].value; val--; //控制其数量的值不能小于1 if(val<=1) { val=1; } txt[this.index].value=val; //把更新了的val值再赋给txt[this.index].value addprice(this.index); //调用一下addprice()使其在当前变化下执行 } btnright[i].index=i; //把i的值赋给btnright[i]的index btnright[i].onclick=function (){ var val=txt[this.index].value; val++; txt[this.index].value=val; addprice(this.index); } //给checkbox添加点击事件 box[i].onclick=function (){ showtotleprice(); } //给删除添加点击事件 btndelete[i].index=i; btndelete[i].onclick=function (){ totleprice-=parseFloat(small[this.index].innerText); //将总计里面对应的价格也减掉 totle.innerText=totleprice; trlist[this.index].remove(); //去掉对应的那一行元素 //重新更新索引 防止其他操作出错 for(var k=0;k<trlist.length;k++) { trlist[k].index=k; btndelete[k].index=k; btnleft[k].index=k; btnright[k].index=k; } } } //计算小计 function addprice(index){ small[index].innerText=(price[index].innerText*txt[index].value); } //计算总计 function showtotleprice(){ totleprice=0; for(var i=0;i<small.length;i++) { if(box[i].checked) { totleprice+=parseFloat(small[i].innerText); } } totle.innerText=totleprice; } //全选 btna.onclick=function (){ for(var i=0;i<box.length;i++) { box[i].checked=true; } showtotleprice(); } //反选 btnf.onclick=function (){ for(var i=0;i<box.length;i++) { box[i].checked=!box[i].checked; } showtotleprice(); } </script>

Related recommendations:

javascript - Business logic of the shopping cart module

Use native JavaScript to implement shopping cart and shopping page

The above is the detailed content of How to implement the shopping cart function in javascript (code). 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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.

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

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.

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor