Relevant DOM operations for developing shopping carts with JavaScript (1)
After designing the homepage, you can perform DOM operations related to the homepage, including click events of adding buttons,
Cookie and json applications, cookies are mainly used to share current data with the shopping cart , to facilitate operation.
Idea:
Step one: Get the node object to be operated
Step two: After the page is loaded, you need to calculate how many local cookies are stored product, assign the number to ccount
Step 3: Bind a click event onclick
to the add shopping cart button corresponding to each product#Change the local cookie
Get the pid of the current product
Loop through the local cookie converted array, take out the pid of each object for comparison, if they are equal, the product is not added for the first time
From the shopping cart Take out the product, and then update the pCount value by appending 1
Otherwise: Create a new object and save it to shopping. At the same time, the quantity of this product is 1
<script> var ccount = document.getElementById("ccount"); //顯示商品總數(shù)量的標(biāo)簽節(jié)點(diǎn)對(duì)象 var btns = document.querySelectorAll(".list dl dd button"); //所有的購(gòu)物車(chē)按鈕 //querySelectorAll返回匹配的元素集合,如果沒(méi)有匹配項(xiàng),返回空的nodelist(節(jié)點(diǎn)數(shù)組)。 //約定好用名稱(chēng)為datas的cookie來(lái)存放購(gòu)物車(chē)?yán)锏臄?shù)據(jù)信息 datas里所存放的就是一個(gè)json字符串 var listStr = cookieObj.get("datas"); /*判斷一下本地是否有一個(gè)購(gòu)物車(chē)(datas),沒(méi)有的話(huà),創(chuàng)建一個(gè)空的購(gòu)物車(chē),有的話(huà)就直接拿來(lái)使用*/ if(!listStr) { //沒(méi)有購(gòu)物車(chē) datas json cookieObj.set({ name: "datas", value: "[]" }); listStr = cookieObj.get("datas"); } var listObj = JSON.parse(listStr); //數(shù)組 /*循環(huán)遍歷數(shù)組,獲取每一個(gè)對(duì)象中的pCount值相加總和*/ var totalCount = 0; //默認(rèn)為0 for(var i = 0, len = listObj.length; i < len; i++) { totalCount = listObj[i].pCount + totalCount; } ccount.innerHTML = totalCount; /*循環(huán)為每一個(gè)按鈕添加點(diǎn)擊事件*/ for(var i = 0, len = btns.length; i < len; i++) { btns[i].onclick = function() { var dl = this.parentNode.parentNode; //parentNode 獲取文檔層次中的父對(duì)象。 var pid = dl.getAttribute("pid");//獲取自定義屬性 //getAttribute() 方法通過(guò)名稱(chēng)獲取屬性的值。 var arrs = dl.children;//獲取所有子節(jié)點(diǎn) 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: pDesc, price: price, pCount: 1 }; listObj.push(obj); //push() 方法可向數(shù)組的末尾添加一個(gè)或多個(gè)元素,并返回新的長(zhǎng)度。 listObj = updateData(listObj); } ccount.innerHTML = getTotalCount(); } } </script>
Create an index.js file and put the above JavaScript code into it.
<script type="text/javascript" src="index.js"></script>
Later called from the HTML page to achieve the function module effect.