本文描述了购买按钮点击事件的编写。
由于最开始写预定按钮时用的是以下代码导致点击按钮时无法获取当前的ID
<button id="book-button">购买</button>
发现这个问题后将代码改为下列形式,使用了模板字符串来动态设置 data-train-id
属性的值,这样可以在不同的上下文中使用不同的 train.id
。
<button type="button" class="buy-button" data-train-id="${train.id}">购买</button>
然后就可以为购买按钮添加点击事件处理程序,点击后出现一个对话框,将车次信息填入表单当中。
可通过以下代码找到当前的车次信息:
var trainId = $(this).data('train-id');
var trainInfo = trains.find(train => train.id === trainId);
首先要创建对话框,并将车次信息填入对话框中,并在最后添加确认购买的按钮。
var purchaseDialogHtml = `
<div id="purchase-dialog" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>您正在购买以下火车票:</p>
<p>用户ID:${user.uid}</p>
<p>车次:${trainInfo.trainNo}</p>
<p>出发时间:${trainInfo.dptTime}</p>
<p>到达时间:${trainInfo.arrTime}</p>
<p>出发站:${trainInfo.dptStationName}</p>
<p>到达站:${trainInfo.arrStationName}</p>
<label for="seat-type">座位类型:</label>
<select id="seat-type">
<option value="商务座">商务座</option>
<option value="一等座">一等座</option>
<option value="二等座">二等座</option>
</select>
<button id="confirm-purchase">确认购买</button>
</div>
</div>`;
接着将购买对话框添加到页面中
$('body').append(purchaseDialogHtml);
当用户点击关闭按钮时,关闭购买对话框
$('.close').on('click', function() {
$('#purchase-dialog').remove(); // 移除购买对话框
});
当用户点击确认购买按钮时,执行购买操作。将对话框中的信息作为一个trainOrder对象传入,使用 jQuery 发送 POST 请求,如果服务器成功处理了请求,会返回一个包含 code 和 message 属性的 JSON 响应。如果响应中 code 为 200 而且 message 为 "success",则会弹出提示框显示 "购买成功!",并移除购买对话框;否则会在控制台输出错误信息。如果发送请求时发生错误,也会在控制台输出相关信息。
$.ajax({
type: "POST",
url: "/train/order",
contentType: "application/json", // 设置请求内容类型为 JSON
data: JSON.stringify(trainOrder), // 将订单对象转换为 JSON 字符串并传入
success: function (response) {
if (response.code === 200 && response.message === "success") {
alert("购买成功!");
$('#purchase-dialog').remove(); // 移除购买对话框
// 可以根据需要执行其他操作,例如跳转到订单页面等
} else {
console.error("购买失败:", response.message);
}
},
error: function (xhr) {
console.error("购买时发生错误:", xhr.status, xhr.statusText);
}
});
同时为了让对话框美观,我们可以对购买对话框样式进行设置,让对话框水平和垂直居中,并设置按钮的位置,颜色,字体大小,以及鼠标悬停时的光标形状。
// 设置购买对话框样式
$('#purchase-dialog').css({
"display": "flex",
"justify-content": "center",
"align-items": "center",
"position": "fixed",
"top": "50%",
"left": "50%",
"transform": "translate(-50%, -50%)",
"background-color": "#f2f2f2",
"padding": "20px",
"width": "300px",
"text-align": "center"
});
// 设置对话框内容区域样式,使其垂直居中
$('.modal-content').css({
"display": "flex",
"flex-direction": "column",
"justify-content": "center",
"align-items": "center"
});
// 设置关闭按钮样式
$('.close').css({
"color": "red",
"position": "absolute",
"top": "5px",
"right": "10px",
"font-size": "24px",
"cursor": "pointer"
});
// 设置购买按钮样式
$('#confirm-purchase').css({
"margin-top": "20px",
"padding": "10px 20px",
"background-color": "green",
"color": "white",
"border": "none",
"border-radius": "5px",
"cursor": "pointer"
});