我想知道为什么在 Chrome 中,这一行:
var quer = confirm("Deseja esta poltrona?");
在上一行之前加载:
imagens[i].src = "img/poltrona_selecionada.jpg";
在 Firefox 上,该函数按顺序完美运行。
这是我的功能:
function selecionarPoltrona() {
var imagens = document.getElementsByTagName("img");
for (var i=0; i<poltronas.length; i++) {
if (poltronas[i]) {
imagens[i].src = "img/poltrona_selecionada.jpg";
var quer = confirm("Deseja esta poltrona?");
if (quer) {
break;
} else {
imagens[i].src = "img/poltrona_disponivel.jpg";
}
}
}
}
谢谢
最佳答案
欢迎使用 Image 对象,以及 <img>
元素:它不是同步的。当您告诉图像的来源是什么时,其余代码就可以继续运行。它不会等待图像绑定(bind)成功、查找图像 URL、传输数据、解码字节,所有这些都在您看到图像之前完成。这一切都是在其余代码运行时发生的。然而,confirm(以及alert、prompt,以及所有那些糟糕的函数)却不会:它们会阻塞线程。所以会发生这种情况:
- 您设置了图像
.src
属性,浏览器安排它进行线程外处理。您的代码继续 -
confirm
被触发,一切都停止了。在处理确认之前,您的选项卡中不会发生任何事情。 - 您点击确认。 JavaScript 再次运行,浏览器的图像源绑定(bind)再次运行。
- X 时间后,您的图像完成下载、解析并最终渲染。
如果您希望在图像完成所有工作之后运行一些代码,您可以这样做:
...
img.onload = function() {
// the code you need to have run after the image finishes loading.
}
img.onerror = function() {
// whatever we need to do if the image cannot load.
}
img.src = "..." // trigger the image loading attempt
或者,使用现代而不是 1998 JS:
...
img.addEventListener("load", function(evt) {
// the code you need to have run after the image finishes loading.
});
img.addEventListeners("error", function(evt) {
// whatever we need to do if the image cannot load.
});
img.src = "..." // trigger the image loading attempt
关于javascript - 为什么在 Chrome 中,confirm() 函数会先加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35106119/