我正在使用 javascript 创建一个程序,同时单击按钮它将选择一个座位并将其背景颜色更改为绿色,同时按钮值将被添加到文本字段中,并将相应地切换,并且在相同的功能中我是传递另一个值,即公共汽车的票价。问题:当我点击一个座位按钮时,它的票价会添加到文本框中,但如果我点击两个或更多座位按钮,票价只会添加到文本框中,但不会计算票价的总和。当我再次点击选定的座位时,票价将从总票价中扣除。这里我没有使用 jquery。请问有人可以帮助我吗?
// Create a variable for the array!
var selectedSeats = new Array();
var selectedFares= new Array();
// Build a function that will update the textfield.
// Call this, whenever the array gets changed!
function updateListOfSelectedSeats() {
document.getElementById('selectedseat').value = selectedSeats.join(',');
document.getElementById('selectedfare').value = selectedFares;
}
// Removes a seat from the list of selected seats
function removeSeatFromList(seat,seatFare) {
for (var i = 0; i < selectedSeats.length; i++) {
if (selectedSeats[i] == seat) {
selectedSeats.splice(i, 1);
updateListOfSelectedSeats();
removeFareFromList(seatFare);
break;
}
}
}
function removeFareFromList(seatFares) {
for (var i = 0; i < selectedFares.length; i++) {
if (selectedFares[i] == seatFares) {
selectedFares.splice(i, 1);
updateListOfSelectedSeats();
break;
}
}
}
// Now the function that reacts to clicks on a seat
function setId(id, value,fare) {
var Seat = document.getElementById(id);
switch (Seat.style.backgroundImage) {
case 'url("themes/frontend/images/greenseat.png")':
// Seat is already selected and needs to be deselected
Seat.style.backgroundImage = 'url("themes/frontend/images/seat.png")';
removeSeatFromList(value,fare);
break;
case '':
case 'url("themes/frontend/images/seat.png")':
// Seat is empty, select it!
Seat.style.backgroundImage = 'url("themes/frontend/images/greenseat.png")';
selectedSeats.push(value);
selectedFares.push(fare);
updateListOfSelectedSeats();
break;
}
}