利用javascript实季点餐页面
时间: 2023-05-14 16:03:40 浏览: 139
如果要利用JavaScript实现一个简单的点餐页面,可以按照以下步骤进行:
1. 设计页面布局:包括菜单、菜品列表、购物车等元素。
2. 编写JavaScript代码:主要是用来添加菜品到购物车、计算总价、提交订单等功能。具体实现可以参考下面的示例代码:
// 定义全局变量
var cart = []; // 购物车数组,保存已选择的菜品
var menu = [ // 菜单数组,保存所有可选的菜品
{name: '牛肉面', price: 15},
{name: '鸡蛋炒饭', price: 10},
{name: '番茄炒蛋', price: 8},
{name: '红烧肉', price: 20}
];
// 将菜品添加到购物车中
function addToCart(index) {
var dish = menu[index];
cart.push(dish);
updateCart(); // 更新购物车显示
}
// 从购物车中删除菜品
function removeFromCart(index) {
cart.splice(index, 1);
updateCart(); // 更新购物车显示
}
// 计算购物车中的总价
function calculateTotalPrice() {
var total = 0;
for (var i = 0; i < cart.length; i++) {
total += cart[i].price;
}
return total;
}
// 更新购物车显示
function updateCart() {
var cartList = document.getElementById('cart-list');
var totalPrice = document.getElementById('total-price');
// 先清空原有的内容
cartList.innerHTML = '';
// 重新生成购物车列表
for (var i = 0; i < cart.length; i++) {
var item = document.createElement('li');
var name = document.createElement('span');
var price = document.createElement('span');
var removeBtn = document.createElement('button');
name.innerText = cart[i].name;
price.innerText = cart[i].price;
removeBtn.innerText = '删除';
removeBtn.onclick = function() { removeFromCart(i); };
item.appendChild(name);
item.appendChild(price);
item.appendChild(removeBtn);
cartList.appendChild(item);
}
// 更新总价显示
totalPrice.innerText = calculateTotalPrice();
}
// 提交订单
function submitOrder() {
if (cart.length === 0) {
alert('您还没有选择任何菜品!')
return;
}
var total = calculateTotalPrice();
alert('您选择的菜品总价为:' + total + '元');
// TODO:将订单发送到服务器处理
}
3. 在HTML页面中引入JavaScript文件,并在需要的地方调用相关函数即可。
以上代码只是一个简单示例,实际应用中可能需要增加更多的功能,如搜索菜品、修改订单等。同时,需要注意保护用户隐私和数据安全,避免出现重复提交订单、SQL注入等问题。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)