app.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. // API 配置
  2. const API_BASE_URL = 'http://localhost:8086/api';
  3. // 支付二维码图片配置(方便更换)
  4. // 请将图片复制到 oederFoodVue/images/ 文件夹,然后使用相对路径
  5. const PAYMENT_QRCODE_IMAGE = 'images/payment-qrcode.jpg';
  6. // 应用状态
  7. const state = {
  8. cart: {}, // { dishId: count } 雪花ID(字符串/数字)唯一键,彻底解决选品关联问题
  9. currentCategory: null,
  10. selectedDish: null,
  11. categories: [],
  12. dishes: []
  13. };
  14. // 工具函数:价格格式化(非数字兜底为0,避免NaN)
  15. function formatPrice(price) {
  16. const num = parseFloat(price);
  17. return isNaN(num) ? 0 : num;
  18. }
  19. // API 调用函数 - 获取分类
  20. async function fetchCategories() {
  21. try {
  22. const response = await fetch(`${API_BASE_URL}/categories`);
  23. const result = await response.json();
  24. if (result.code === 200) {
  25. state.categories = result.data || [];
  26. if (state.categories.length > 0 && !state.currentCategory) {
  27. state.currentCategory = parseInt(state.categories[0].id);
  28. }
  29. } else {
  30. console.error('获取分类失败:', result.message);
  31. alert('获取分类失败: ' + result.message);
  32. }
  33. } catch (error) {
  34. console.error('获取分类出错:', error);
  35. alert('获取分类出错,请检查后端服务是否启动');
  36. }
  37. }
  38. // API 调用函数 - 获取菜品
  39. async function fetchDishes() {
  40. try {
  41. const response = await fetch(`${API_BASE_URL}/dishes`);
  42. const result = await response.json();
  43. if (result.code === 200) {
  44. state.dishes = result.data || [];
  45. } else {
  46. console.error('获取菜品失败:', result.message);
  47. alert('获取菜品失败: ' + result.message);
  48. }
  49. } catch (error) {
  50. console.error('获取菜品出错:', error);
  51. alert('获取菜品出错,请检查后端服务是否启动');
  52. }
  53. }
  54. // 初始化
  55. async function init() {
  56. // 加载提示
  57. document.getElementById('dishContainer').innerHTML = '<div style="text-align:center;padding:40px;color:#999;">加载中...</div>';
  58. // 并行请求数据,提升速度
  59. await Promise.all([fetchCategories(), fetchDishes()]);
  60. // 渲染页面
  61. renderCategories();
  62. renderDishes();
  63. bindEvents();
  64. }
  65. // 渲染分类列表
  66. function renderCategories() {
  67. const categoryList = document.getElementById('categoryList');
  68. if (state.categories.length === 0) {
  69. categoryList.innerHTML = '<div style="padding:20px;text-align:center;color:#999;">暂无分类</div>';
  70. return;
  71. }
  72. categoryList.innerHTML = state.categories.map(cat => {
  73. const catId = cat.id; // 后端返回的字符串ID
  74. const currentId = state.currentCategory; // 直接用字符串ID,不转数字
  75. return `
  76. <div class="category-item ${catId === currentId ? 'active' : ''}" data-id="${catId}">
  77. ${cat.categoryName}
  78. </div>
  79. `}).join('');
  80. }
  81. // 渲染菜品列表 - 全程字符串ID,无任何parseInt,彻底解决精度丢失/ID不匹配
  82. function renderDishes() {
  83. const dishContainer = document.getElementById('dishContainer');
  84. if (state.dishes.length === 0) {
  85. dishContainer.innerHTML = '<div style="text-align:center;padding:40px;color:#999;">暂无菜品</div>';
  86. return;
  87. }
  88. // 过滤有菜品的分类:字符串ID严格相等对比,无任何转换
  89. const categoriesWithDishes = state.categories.filter(cat =>
  90. state.dishes.some(dish => dish.categoryId === cat.id)
  91. );
  92. if (categoriesWithDishes.length === 0) {
  93. dishContainer.innerHTML = '<div style="text-align:center;padding:40px;color:#999;">暂无菜品</div>';
  94. return;
  95. }
  96. // 按分类渲染菜品,全程字符串ID,data-id唯一绑定
  97. dishContainer.innerHTML = categoriesWithDishes.map(category => {
  98. const categoryId = category.id; // 纯字符串分类ID,不做任何转换
  99. // 过滤当前分类的菜品:字符串categoryId严格相等对比
  100. const dishes = state.dishes.filter(dish => dish.categoryId === categoryId);
  101. return `
  102. <div class="category-section" id="category-${categoryId}"> <!-- 字符串ID拼接,和点击的ID完全一致 -->
  103. <h3 class="category-title">${category.categoryName}</h3>
  104. <div class="dish-list">${dishes.map(dish => {
  105. const imgUrl = dish.coverImg || 'https://picsum.photos/100/100?text=菜品图片';
  106. const description = dish.description || '暂无描述';
  107. const tasteFeature = dish.tasteFeature || '美味';
  108. const adaptScene = dish.adaptScene || '推荐';
  109. const sales = dish.sales || 0;
  110. const dishId = dish.id; // 保留雪花ID原始字符串值,不做任何转换
  111. const inCart = state.cart[dishId]; // 仅匹配当前dishId的购物车状态
  112. return `
  113. <div class="dish-item ${inCart ? 'in-cart' : ''}" data-id="${dishId}">
  114. <img class="dish-img" src="${imgUrl}" alt="${dish.dishName}" onerror="this.src='https://picsum.photos/100/100?text=菜品图片'">
  115. <div class="dish-info">
  116. <div class="dish-name">${dish.dishName}</div>
  117. <div class="dish-desc">${description}</div>
  118. <div class="dish-tags">
  119. <span class="dish-tag">${tasteFeature}</span>
  120. <span class="dish-tag">${adaptScene}</span>
  121. </div>
  122. <div class="dish-footer">
  123. <div>
  124. <span class="dish-price">¥${formatPrice(dish.price).toFixed(2)}</span>
  125. <span class="dish-sales">月售${sales}</span>
  126. </div>
  127. <div class="dish-controls">
  128. ${inCart ? `
  129. <button class="control-btn minus" data-action="minus" data-id="${dishId}">-</button>
  130. <span class="dish-count">${inCart}</span>
  131. ` : ''}
  132. <button class="control-btn plus" data-action="plus" data-id="${dishId}">+</button>
  133. </div>
  134. </div>
  135. </div>
  136. </div>
  137. `}).join('')}
  138. </div>
  139. </div>
  140. `;
  141. }).join('');
  142. }
  143. // 更新购物车 - 核心:按dishId唯一计算,不混淆
  144. function updateCart() {
  145. // 计算总数量(仅累加当前dishId的数量)
  146. const totalCount = Object.values(state.cart).reduce((sum, count) => sum + (Number(count) || 0), 0);
  147. // 计算总价(按dishId匹配菜品,精准计算)
  148. const totalPrice = Object.entries(state.cart).reduce((sum, [dishId, count]) => {
  149. const dish = state.dishes.find(d => d.id === dishId); // 精准匹配dishId
  150. return sum + (dish ? formatPrice(dish.price) * (Number(count) || 0) : 0);
  151. }, 0);
  152. // 更新购物车角标
  153. const cartCountEl = document.getElementById('cartCount');
  154. const cartIconEl = document.querySelector('.cart-icon');
  155. cartCountEl.textContent = totalCount;
  156. totalCount > 0 ? (cartCountEl.classList.add('show'), cartIconEl.classList.add('has-items')) : (cartCountEl.classList.remove('show'), cartIconEl.classList.remove('has-items'));
  157. // 更新总价和结算按钮
  158. document.getElementById('totalPrice').textContent = `¥${totalPrice.toFixed(2)}`;
  159. const checkoutBtn = document.getElementById('checkoutBtn');
  160. // 取消起送门槛,只要有商品就可以结算
  161. if (totalCount > 0) {
  162. checkoutBtn.disabled = false;
  163. checkoutBtn.textContent = `去结算(总计¥${totalPrice.toFixed(2)})`;
  164. } else {
  165. checkoutBtn.disabled = true;
  166. checkoutBtn.textContent = `去结算`;
  167. }
  168. // 局部更新,不重渲染整个列表(性能优化+避免选品关联)
  169. renderCartDetail();
  170. updateDishCartStatus();
  171. }
  172. // 局部更新菜品购物车状态 - 核心:按dishId精准更新单个菜品,不影响其他
  173. function updateDishCartStatus() {
  174. document.querySelectorAll('.dish-item').forEach(dishItem => {
  175. const dishId = dishItem.dataset.id; // 单独获取每个菜品的dishId
  176. const inCart = state.cart[dishId]; // 仅判断当前dishId的购物车状态
  177. const controlsDiv = dishItem.querySelector('.dish-controls');
  178. // 单独更新当前菜品的选中样式
  179. inCart ? dishItem.classList.add('in-cart') : dishItem.classList.remove('in-cart');
  180. // 单独更新当前菜品的加减按钮
  181. if (inCart) {
  182. controlsDiv.innerHTML = `
  183. <button class="control-btn minus" data-action="minus" data-id="${dishId}">-</button>
  184. <span class="dish-count">${inCart}</span>
  185. <button class="control-btn plus" data-action="plus" data-id="${dishId}">+</button>
  186. `;
  187. } else {
  188. controlsDiv.innerHTML = `<button class="control-btn plus" data-action="plus" data-id="${dishId}">+</button>`;
  189. }
  190. });
  191. }
  192. // 渲染购物车详情 - 按dishId精准展示
  193. function renderCartDetail() {
  194. const cartDetailList = document.getElementById('cartDetailList');
  195. const cartItems = Object.entries(state.cart).map(([dishId, count]) => {
  196. const dish = state.dishes.find(d => d.id === dishId);
  197. return dish ? { ...dish, count } : null;
  198. }).filter(Boolean);
  199. if (cartItems.length === 0) {
  200. cartDetailList.innerHTML = '<div style="text-align:center;padding:40px;color:#999;">购物车是空的,快来添加菜品吧~</div>';
  201. return;
  202. }
  203. cartDetailList.innerHTML = cartItems.map(item => `
  204. <div class="cart-item">
  205. <span class="cart-item-name">${item.dishName}</span>
  206. <span class="cart-item-price">¥${formatPrice(item.price).toFixed(2)}</span>
  207. <div class="dish-controls">
  208. <button class="control-btn minus" data-action="minus" data-id="${item.id}">-</button>
  209. <span class="dish-count">${item.count}</span>
  210. <button class="control-btn plus" data-action="plus" data-id="${item.id}">+</button>
  211. </div>
  212. </div>
  213. `).join('');
  214. }
  215. // 更新菜品数量 - 核心:dishId全程唯一,操作仅影响当前菜品
  216. function updateDishCount(dishId, action) {
  217. console.log('=== updateDishCount ===');
  218. console.log('dishId:', dishId, 'type:', typeof dishId);
  219. console.log('action:', action);
  220. console.log('购物车 before:', JSON.stringify(state.cart));
  221. if (action === 'plus') {
  222. state.cart[dishId] = (state.cart[dishId] || 0) + 1;
  223. // 首次加购提示
  224. if (Object.keys(state.cart).length === 1 && state.cart[dishId] === 1) showCartTip();
  225. } else if (action === 'minus') {
  226. state.cart[dishId] > 1 ? state.cart[dishId]-- : delete state.cart[dishId];
  227. }
  228. console.log('购物车 after:', JSON.stringify(state.cart));
  229. console.log('购物车键:', Object.keys(state.cart));
  230. console.log('购物车值:', Object.values(state.cart));
  231. updateCart(); // 仅更新当前菜品相关状态
  232. }
  233. // 购物车加购提示
  234. function showCartTip() {
  235. const tip = document.getElementById('cartTip');
  236. if (tip) {
  237. tip.classList.add('show');
  238. setTimeout(() => tip.classList.remove('show'), 3000);
  239. }
  240. }
  241. // 显示菜品详情 - 按dishId精准匹配
  242. function showDishDetail(dishId) {
  243. const dish = state.dishes.find(d => d.id === dishId);
  244. if (!dish) return;
  245. state.selectedDish = dish;
  246. const imgUrl = dish.coverImg || 'https://picsum.photos/400/400?text=菜品详情';
  247. document.getElementById('dishDetailImg').src = imgUrl;
  248. document.getElementById('dishDetailImg').onerror = () => this.src = 'https://picsum.photos/400/400?text=菜品详情';
  249. document.getElementById('dishDetailName').textContent = dish.dishName;
  250. document.getElementById('dishDetailDesc').textContent = dish.description || '暂无描述';
  251. document.getElementById('dishDetailPrice').textContent = formatPrice(dish.price).toFixed(2);
  252. document.getElementById('dishDetailTags').innerHTML = `
  253. <span class="dish-tag">${dish.tasteFeature || '美味'}</span>
  254. <span class="dish-tag">${dish.adaptScene || '推荐'}</span>
  255. <span class="dish-tag">月售${dish.sales || 0}</span>
  256. `;
  257. document.getElementById('dishDetailMask').classList.add('show');
  258. document.getElementById('dishDetail').classList.add('show');
  259. }
  260. // 隐藏菜品详情
  261. function hideDishDetail() {
  262. document.getElementById('dishDetailMask').classList.remove('show');
  263. document.getElementById('dishDetail').classList.remove('show');
  264. }
  265. // 切换购物车详情
  266. function toggleCartDetail() {
  267. console.log('=== toggleCartDetail ===');
  268. console.log('state.cart:', state.cart);
  269. console.log('购物车键:', Object.keys(state.cart));
  270. console.log('购物车值:', Object.values(state.cart));
  271. const totalCount = Object.values(state.cart).reduce((sum, count) => sum + (Number(count) || 0), 0);
  272. console.log('总数量:', totalCount);
  273. if (totalCount === 0) {
  274. alert('购物车为空,无法打开~');
  275. return;
  276. }
  277. const mask = document.getElementById('cartMask');
  278. const detail = document.getElementById('cartDetail');
  279. mask.classList.contains('show') ? (mask.classList.remove('show'), detail.classList.remove('show')) : (mask.classList.add('show'), detail.classList.add('show'));
  280. }
  281. // 清空购物车
  282. function clearCart() {
  283. if (confirm('确定要清空购物车吗?清空后将恢复为空~')) {
  284. state.cart = {};
  285. updateCart();
  286. toggleCartDetail();
  287. }
  288. }
  289. // 结算功能 - 先显示二维码,支付成功后创建订单
  290. async function checkout() {
  291. const totalPrice = Object.entries(state.cart).reduce((sum, [dishId, count]) => {
  292. const dish = state.dishes.find(d => d.id === dishId);
  293. return sum + (dish ? formatPrice(dish.price) * (Number(count) || 0) : 0);
  294. }, 0);
  295. // 取消起送门槛检查,只要有商品就可以结算
  296. if (totalPrice <= 0) {
  297. alert('购物车是空的,请先添加商品~');
  298. return;
  299. }
  300. // 准备订单数据(暂存,支付成功后再提交)
  301. const orderData = {
  302. items: Object.entries(state.cart).map(([dishId, quantity]) => ({
  303. dishId: dishId,
  304. quantity: quantity
  305. })),
  306. totalAmount: totalPrice,
  307. deliveryFee: 0,
  308. finalAmount: totalPrice,
  309. remark: ''
  310. };
  311. // 直接显示支付二维码
  312. showPaymentQRCode(orderData);
  313. }
  314. // 显示支付二维码
  315. function showPaymentQRCode(orderData) {
  316. // 生成临时支付单号用于验证
  317. const paymentId = 'PAY' + Date.now();
  318. // 显示订单信息
  319. document.getElementById('payOrderNumber').textContent = paymentId;
  320. document.getElementById('payAmount').textContent = `¥${orderData.finalAmount.toFixed(2)}`;
  321. // 设置二维码图片
  322. const qrcodeImage = document.getElementById('qrcodeImage');
  323. qrcodeImage.src = PAYMENT_QRCODE_IMAGE;
  324. qrcodeImage.onerror = function() {
  325. this.src = 'https://via.placeholder.com/200x200/4caf50/ffffff?text=请添加支付二维码';
  326. };
  327. // 显示支付弹窗
  328. document.getElementById('paymentMask').classList.add('show');
  329. document.getElementById('paymentModal').classList.add('show');
  330. // 开始轮询支付状态(传入支付单号和订单数据)
  331. startPaymentPolling(paymentId, orderData);
  332. }
  333. // 轮询支付状态
  334. let paymentPollingTimer = null;
  335. let pollingCount = 0;
  336. const MAX_POLLING_COUNT = 60; // 最多轮询60次(2分钟)
  337. function startPaymentPolling(paymentId, orderData) {
  338. if (paymentPollingTimer) clearInterval(paymentPollingTimer);
  339. pollingCount = 0;
  340. // 每2秒轮询一次支付状态
  341. paymentPollingTimer = setInterval(async () => {
  342. pollingCount++;
  343. // 超时处理
  344. if (pollingCount > MAX_POLLING_COUNT) {
  345. stopPaymentPolling();
  346. showPaymentFailure('支付超时,请重新下单');
  347. return;
  348. }
  349. try {
  350. // 调用后端验证支付状态
  351. const response = await fetch(`${API_BASE_URL}/payment/verify?paymentId=${paymentId}`);
  352. const result = await response.json();
  353. if (result.code === 200 && result.data.paid) {
  354. // 支付成功,停止轮询
  355. stopPaymentPolling();
  356. // 创建订单
  357. await createOrderAfterPayment(orderData);
  358. } else if (result.code === 200 && result.data.failed) {
  359. // 支付失败
  360. stopPaymentPolling();
  361. showPaymentFailure('支付失败,请重试');
  362. }
  363. // 如果是待支付状态,继续轮询
  364. } catch (error) {
  365. console.error('验证支付状态失败:', error);
  366. }
  367. }, 2000);
  368. }
  369. // 支付成功后创建订单
  370. async function createOrderAfterPayment(orderData) {
  371. try {
  372. const response = await fetch(`${API_BASE_URL}/orders`, {
  373. method: 'POST',
  374. headers: {
  375. 'Content-Type': 'application/json'
  376. },
  377. body: JSON.stringify(orderData)
  378. });
  379. const result = await response.json();
  380. if (result.code === 200) {
  381. showPaymentSuccess();
  382. } else {
  383. showPaymentFailure('订单创建失败: ' + result.message);
  384. }
  385. } catch (error) {
  386. console.error('创建订单失败:', error);
  387. showPaymentFailure('订单创建失败,请联系客服');
  388. }
  389. }
  390. function stopPaymentPolling() {
  391. if (paymentPollingTimer) {
  392. clearInterval(paymentPollingTimer);
  393. paymentPollingTimer = null;
  394. }
  395. pollingCount = 0;
  396. }
  397. // 显示支付失败
  398. function showPaymentFailure(message) {
  399. document.getElementById('paymentStatus').innerHTML = `
  400. <div class="status-failure show">
  401. <div class="failure-icon">✗</div>
  402. <p>${message}</p>
  403. </div>
  404. `;
  405. setTimeout(() => {
  406. closePaymentModal();
  407. }, 3000);
  408. }
  409. function showPaymentSuccess() {
  410. document.getElementById('paymentStatus').innerHTML = `
  411. <div class="status-success show">
  412. <div class="success-icon">✓</div>
  413. <p>支付成功!</p>
  414. </div>
  415. `;
  416. setTimeout(() => {
  417. closePaymentModal();
  418. state.cart = {};
  419. updateCart();
  420. const mask = document.getElementById('cartMask');
  421. const detail = document.getElementById('cartDetail');
  422. mask.classList.remove('show');
  423. detail.classList.remove('show');
  424. alert('支付成功!我们将尽快为您配送~');
  425. }, 2000);
  426. }
  427. function closePaymentModal() {
  428. stopPaymentPolling();
  429. document.getElementById('paymentMask').classList.remove('show');
  430. document.getElementById('paymentModal').classList.remove('show');
  431. document.getElementById('paymentStatus').innerHTML = `
  432. <div class="status-checking">
  433. <div class="loading-spinner"></div>
  434. <p>等待支付中...</p>
  435. </div>
  436. `;
  437. }
  438. // 事件绑定 - 核心:事件委托精准获取当前dishId,不混淆
  439. function bindEvents() {
  440. // 分类切换
  441. document.getElementById('categoryList').addEventListener('click', (e) => {
  442. const item = e.target.closest('.category-item');
  443. if (item) {
  444. const categoryId = item.dataset.id;
  445. state.currentCategory = categoryId;
  446. console.log('=== 分类切换 ===');
  447. console.log('目标分类 ID:', categoryId);
  448. renderCategories();
  449. // 【补充】分类切换时建议重新渲染菜品(确保菜品区域和分类同步)
  450. renderDishes();
  451. // 使用 requestAnimationFrame 确保 DOM 完全更新(双重帧足够等待渲染)
  452. requestAnimationFrame(() => {
  453. requestAnimationFrame(() => {
  454. // 错误1修复:拼接正确的分类区域ID → category-xxx
  455. const section = document.getElementById(`category-${categoryId}`);
  456. // 错误2修复:修正滚动容器类名 → .dish-container(和渲染一致)
  457. const container = document.querySelector('.dish-container');
  458. console.log('分类区域元素:', section);
  459. console.log('滚动容器:', container);
  460. if (section && container) {
  461. section.scrollIntoView({
  462. behavior: 'smooth',
  463. block: 'start' // 贴顶显示,体验更好
  464. });
  465. console.log('滚动成功:已定位到分类 →', `category-${categoryId}`);
  466. } else {
  467. // 分情况提示错误,方便排查
  468. if (!section) {
  469. console.warn('滚动失败:未找到分类区域元素,可能该分类无菜品', `ID: category-${categoryId}`);
  470. }
  471. if (!container) {
  472. console.error('滚动失败:未找到菜品滚动容器,请检查类名是否为 .dish-container');
  473. }
  474. }
  475. });
  476. });
  477. }
  478. });
  479. // 以下是你原有的其他事件逻辑(菜品操作、购物车、详情等),保留不变即可
  480. // 菜品操作 - 精准获取当前点击按钮的dishId
  481. document.getElementById('dishContainer').addEventListener('click', (e) => {
  482. const btn = e.target.closest('.control-btn');
  483. if (btn) {
  484. e.stopPropagation();
  485. const dishId = btn.dataset.id;
  486. const action = btn.dataset.action;
  487. updateDishCount(dishId, action);
  488. return;
  489. }
  490. // 菜品详情
  491. const dishItem = e.target.closest('.dish-item');
  492. dishItem && showDishDetail(dishItem.dataset.id);
  493. });
  494. // 购物车图标
  495. document.getElementById('cartIcon').addEventListener('click', toggleCartDetail);
  496. // 购物车遮罩
  497. document.getElementById('cartMask').addEventListener('click', toggleCartDetail);
  498. // 购物车内部操作
  499. document.getElementById('cartDetailList').addEventListener('click', (e) => {
  500. const btn = e.target.closest('.control-btn');
  501. btn && updateDishCount(btn.dataset.id, btn.dataset.action);
  502. });
  503. // 清空购物车
  504. document.getElementById('clearCart').addEventListener('click', (e) => {
  505. e.stopPropagation();
  506. clearCart();
  507. });
  508. // 结算按钮
  509. document.getElementById('checkoutBtn').addEventListener('click', (e) => {
  510. e.stopPropagation();
  511. checkout();
  512. });
  513. // 菜品详情操作
  514. document.getElementById('addToCartBtn').addEventListener('click', () => {
  515. state.selectedDish && (updateDishCount(state.selectedDish.id, 'plus'), hideDishDetail());
  516. });
  517. document.getElementById('closeDetail').addEventListener('click', hideDishDetail);
  518. document.getElementById('dishDetailMask').addEventListener('click', hideDishDetail);
  519. document.getElementById('dishDetail').addEventListener('click', (e) => e.stopPropagation());
  520. // 支付弹窗事件
  521. document.getElementById('closePayment').addEventListener('click', closePaymentModal);
  522. document.getElementById('paymentMask').addEventListener('click', closePaymentModal);
  523. document.getElementById('paymentModal').addEventListener('click', (e) => e.stopPropagation());
  524. }
  525. // 页面加载完成初始化
  526. document.addEventListener('DOMContentLoaded', init);