题解 | #购物面板#
购物面板
https://www.nowcoder.com/practice/1448469386f746f5941db2712372f373
{"html":"<!-- 请补全JavaScript代码,要求如下:\r\n1. 当点击\"-\"按钮时,商品数量减1\r\n2. 当点击\"+\"按钮时,商品数量加1\r\n3. 每当点击任意按钮时,购物面板中相关信息必须同步更新\r\n注意:\r\n1. 必须使用DOM0级标准事件(onclick) -->\r\n<!DOCTYPE html>\r\n<html>\r\n\r\n<head>\r\n <meta charset=utf-8>\r\n</head>\r\n\r\n<body>\r\n <table>\r\n <thead>\r\n <caption>\r\n 商品\r\n </caption>\r\n </thead>\r\n <tbody>\r\n <tr>\r\n <td>炸鸡</td>\r\n <td>28元</td>\r\n <td><button id=\"zjtaiduola\" data-type=\"reducezj\">-</button></td>\r\n <td><span id=\"zjsl\">0</span></td>\r\n <td><button id=\"zjtaishaola\" data-type=\"addzj\">+</button></td>\r\n </tr>\r\n <tr>\r\n <td>可乐</td>\r\n <td>5元</td>\r\n <td><button id=\"kltaiduola\" data-type=\"reducekl\">-</button></td>\r\n <td><span id=\"klsl\">0</span></td>\r\n <td><button id=\"kltaishaola\" data-type=\"addkl\">+</button></td>\r\n </tr>\r\n <tr>\r\n <td>总价:</td>\r\n <td><span id=\"total\">0</span></td>\r\n </tr>\r\n </tbody>\r\n </table>\r\n\r\n <script type=\"text/javascript\">\r\n // 补全代码\r\n const zhaji = document.querySelector('#zjsl')\r\n const coco = document.querySelector(\"#klsl\")\r\n let zhajiNum = +zhaji.innerHTML\r\n let cocoNum = +coco.innerHTML\r\n const zjPrrice = +(document.querySelector('tbody tr:nth-child(1) :nth-child(2)').innerHTML)\r\n const klPrice = +(document.querySelector('tbody tr:nth-child(2) :nth-child(2)').innerHTML)\r\n document.querySelector(\"#zjtaishaola\").onclick = addGoods\r\n document.querySelector(\"#kltaishaola\").onclick = addGoods\r\n document.querySelector(\"#zjtaiduola\").onclick = reduceGoods\r\n document.querySelector(\"#kltaiduola\").onclick = reduceGoods\r\n // document.querySelector(\"#zjtaishaola\").addEventListener('click', function (e) {\r\n // })\r\n function addGoods(e) {\r\n // console.log(e.target.dataset.type);\r\n if (e.target.dataset.type === 'addzj') {\r\n // console.log(zhajiNum);\r\n zhaji.innerHTML = ++zhajiNum\r\n renderSum()\r\n } else if (e.target.dataset.type === 'addkl') {\r\n // console.log(zhajiNum);\r\n coco.innerHTML = ++cocoNum\r\n renderSum()\r\n }\r\n }\r\n\r\n\r\n function reduceGoods(e) {\r\n // console.log(e.target.dataset.type);\r\n if (e.target.dataset.type === 'reducezj') {\r\n // console.log(zhajiNum);\r\n if (zhajiNum < 1) return alert(\"数量不可小于0\")\r\n zhaji.innerHTML = --zhajiNum\r\n renderSum()\r\n } else if (e.target.dataset.type === 'reducekl') {\r\n // console.log(zhajiNum);\r\n if (cocoNum < 1) return alert(\"数量不可小于0\")\r\n coco.innerHTML = --cocoNum\r\n renderSum()\r\n }\r\n }\r\n\r\n function renderSum() {\r\n document.querySelector('#total').innerHTML = +(28 * zhajiNum + 5 * cocoNum)\r\n }\r\n </script>\r\n</body>\r\n\r\n</html>","css":"/* html, body {\\n\\twidth: 100%;\\n\\theight: 100%;\\n\\tmargin: 0;\\n\\tpadding: 0;\\n} */","js":"// 请在这里输入代码"}