[英]Javascript: how to make changes to the document before function finishes running?
我想创建一个函数,该函数在调用时将显示“正在加载...”消息,并在完成后立即显示结果。 当我这样做时:
function load() {
$('#status').html("loading...");
/* do something */
...
$('#status').html("done");
$('results').html(result);
}
一段时间后,用户看到的只是“完成”消息和结果,因此“加载”消息永远不会出现。 我如何才能使“正在加载”的文本出现在我想要的那一刻?
如果“做某事”是同步的,则浏览器将永远没有机会在两个内容更改之间更新UI。
要显示更改,您需要执行以下操作:
$('#status').html('loading...');
setTimeout(function() {
// do something
$('#status').html('done');
}, 0);
setTimeout
调用使UI有机会在跳入“东西”之前更新显示。
请注意,如果可能的话,您应尝试确保“某物” 不会长时间阻塞您的浏览器。 尝试将任务分解为多个块,其中每个块也使用setTimeout()
调度。
在看不到“填充”部分的情况下很难说出来,但是我希望这可以有所帮助。
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)
}
关键在于“做某事”。 这取决于您要执行的操作,但我希望您希望使用jQuery的load()函数。
许多jQuery函数接受在任务完成后执行的“回调函数”。 load()文档的回调函数部分应说明所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.