为什么在使用 document.getElementByID 更新图像之前显示我的 JavaScript 警报消息?
在我的 JavaScript 代码中,我首先调用一个函数来更新图像:
document.getElementByID("i1").src = newImage;
然后调用几个语句后,调用alert()函数来显示一条消息:
alert("image updated!");
但是,当我运行此代码时,实际发生的是弹出警报框在图像更新之前。当我单击对话框中的“确定”按钮以关闭警报框时,图像会更新。
为什么不保留这些事件的顺序?在显示警报对话框之前,是否可以调用某种同步函数来等待图像更新完成?
我愿意以某种方式重组代码(即使用alert() 函数以外的其他方法),但我更喜欢一种允许现有代码按预期工作的解决方案。
In my JavaScript code I am first calling a function to update an image:
document.getElementByID("i1").src = newImage;
then a few statements later the alert() function is called to display a message:
alert("image updated!");
However, when I run this code, what actually happens is that the alert box is popped up before the image is updated. When I click the "OK" button in the dialog to take the alert box down, the image updates.
Why is the order of these events not being preserved? And is there some kind of synchronizing function I can call to wait for the image update to complete before the alert dialog is displayed?
I'm open to restructuring the code in some ways (i.e., using something other than the alert() function), but I'd prefer a solution that allows the existing code to work as intended.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
图像加载是异步的。您需要的是加载图像时的回调。
如果您使用 jQuery,您可以这样做:
如果您使用 Prototype,您可以这样做:
请注意,无论哪种情况,首先定义回调,然后设置图像 src 都很重要。
Image loading is asynchronous. What you need is a callback for when the image is loaded.
If you are using jQuery, you can do it like this:
If you are using Prototype, you can do it this way:
Note that in either case it's important that you first define the callback, then set the image src.
简单的。
设置图像的 src 属性会启动图像的加载。但由于加载是异步发生的,因此警告框会在加载完成之前显示。
Simple.
Setting the src property of the image initiates the loading of the image. But since the loading happens asynchroneously, the alert box displays before the loading completes.
警报框会阻止后台图像的更新。浏览器所做的是下载图像(您可以使用wireshark或类似的东西看到这一点),但在执行JavaScript时浏览器不会更改网页上的任何内容。如果您有计算密集型 javascript 方法,请尝试使用 WebWorkers。
The alert box blocks the updating of the image in the background. What the browser does is the downloading of the image (you can see this with wireshark or something similar) but the browser doesn't change anything on the web page while JavaScript is executed. If you have computationally intensive javascript methods, try using WebWorkers.