我正在尝试从Head First Javascript(Morrison)一书中学习Javascript。
在函数findSeat()中,代码应该为每个可用的座位更新图像为'seat_select.png',然后要求确认。
但是,当我运行代码时,图像会立即更新(正如预期的那样)。否则,只有在循环完成后才会更新图像。
为什么会这样?
<html>
<head>
<title>Movie Ticket Finder</title>
<script type="text/javascript">
var seats = [ false, true, false, true, true, true, false, true, false ];
var selSeat = -1;
function initSeats() {
// Initialize the appearance of all seats
for (var i = 0; i < seats.length; i++) {
if (seats[i]) {
// Set the seat to available
document.getElementById("seat" + i).src = "seat_avail.png";
document.getElementById("seat" + i).alt = "Available seat";
}
else {
// Set the seat to unavailable
document.getElementById("seat" + i).src = "seat_unavail.png";
document.getElementById("seat" + i).alt = "Unavailable seat";
}
}
}
function findSeat() {
// If seat is already selected, reinitialize all seats to clear them
if (selSeat >= 0) {
selSeat = -1;
initSeats();
}
// Search through all the seats for availability
for (var i = 0; i < seats.length; i++) {
// See if the current seat is available
if (seats[i]) {
// Set the seat selection and update the appearance of the seat
selSeat = i;
document.getElementById("seat" + i).src = "seat_select.png";
document.getElementById("seat" + i).alt = "Your seat";
// Prompt the user to accept the seat
var accept = confirm("Seat " + (i + 1) + " is available. Accept?");
if (!accept) {
// The user rejected the seat, so clear the seat selection and keep looking
selSeat = -1;
document.getElementById("seat" + i).src = "seat_avail.png";
document.getElementById("seat" + i).alt = "Available seat";
}
}
}
}
</script>
</head>
<body onload="initSeats();">
<div style="margin-top:75px; text-align:center">
<img id="seat0" src="" alt="" />
<img id="seat1" src="" alt="" />
<img id="seat2" src="" alt="" />
<img id="seat3" src="" alt="" />
<img id="seat4" src="" alt="" />
<img id="seat5" src="" alt="" />
<img id="seat6" src="" alt="" />
<img id="seat7" src="" alt="" />
<img id="seat8" src="" alt="" /><br />
<input type="button" id="findseat" value="Find Seat" onclick="findSeat();" />
</div>
</body>
</html>
编辑:基于Oleg Yudovich的回答,这是我添加到我的代码中的内容。现在一切都按预期工作了!
<div style="display: none">
<img id="seat_unavail" src="seat_unavail.png" alt="" />
<img id="seat_avail" src="seat_avail.png" alt="" />
<img id="seat_select" src="seat_select.png" alt="" />
</div>
答案 0 :(得分:0)
在html中包含新图像后,您的浏览器会在显示之前下载此图像并将其放入缓存中。此过程需要一些时间。如果您的图像尺寸较大,则需要更多时间。因此,您可以在循环开始运行之前缓存图像来解决问题:
<div style="display:none;">
<img id="seat0" src="some image source" alt=""/>
<img id="seat0" src="some image source" alt=""/>
<img id="seat0" src="some image source" alt=""/>
<img id="seat0" src="some image source" alt=""/>
<img id="seat0" src="some image source" alt=""/>
<img id="seat0" src="some image source" alt=""/>
</div>
这个隐藏的块,如果你将他放在你的网站开始页面,将把所有图像加载到浏览器缓存中。