[英]Javascript: how to make changes to the document before function finishes running?
I want to create a function that when called would display a "Loading..." message, and display the results as soon as it finishes. 我想创建一个函数,该函数在调用时将显示“正在加载...”消息,并在完成后立即显示结果。 when I do it like this:
当我这样做时:
function load() {
$('#status').html("loading...");
/* do something */
...
$('#status').html("done");
$('results').html(result);
}
The "loading" message never appears, after a while what a user sees is just the "done" message and the results. 一段时间后,用户看到的只是“完成”消息和结果,因此“加载”消息永远不会出现。 How can I make the "loading" text appear just the moment I want it to?
我如何才能使“正在加载”的文本出现在我想要的那一刻?
If "do something" is synchronous, the browser never gets a chance to update the UI between the two content changes. 如果“做某事”是同步的,则浏览器将永远没有机会在两个内容更改之间更新UI。
To have the changes appear you need to do something like: 要显示更改,您需要执行以下操作:
$('#status').html('loading...');
setTimeout(function() {
// do something
$('#status').html('done');
}, 0);
The setTimeout
call gives the UI a chance to update the display before jumping into your "something". setTimeout
调用使UI有机会在跳入“东西”之前更新显示。
Note that if possible you should try to ensure that "something" doesn't tie up your browser for a long time. 请注意,如果可能的话,您应尝试确保“某物” 不会长时间阻塞您的浏览器。 Try to break the task up into multiple chunks, where each chunk is also dispatched using
setTimeout()
. 尝试将任务分解为多个块,其中每个块也使用
setTimeout()
调度。
Hard to tell without seeing the "stuff" part, but I hope this helps a little; 在看不到“填充”部分的情况下很难说出来,但是我希望这可以有所帮助。
function load() {
$('#status').html("loading...");
function onLoaded(result) {
$('#status').html("done");
$('results').html(result);
}
// do your stuff here
// Not being able to see the "stuff", I guess you do some AJAX or something
// else which is asynchronous? if you do, at the end of your callback, add
// onLoaded(result)
}
The key is in the "do something". 关键在于“做某事”。 It depends on what you want to do but I would expect that you want to use jQuery's load() function.
这取决于您要执行的操作,但我希望您希望使用jQuery的load()函数。
Many jQuery functions accept 'callback functions' which are executed after the task is complete. 许多jQuery函数接受在任务完成后执行的“回调函数”。 The callback function section of the load() documentation should explain everything.
load()文档的回调函数部分应说明所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.