Hec*_*ksa 1 html javascript jquery
我正在使用jQuery .hide()和.show()函数来显示加载消息,同时执行可能很长的同步webservice调用.
单击下面代码段中的按钮时,我希望文本"Some data"立即替换为"Loading ...",然后在5秒后返回"其他一些数据".
如您所见,这不是发生的事情:
function run_test() {
$('#test1').hide();
$('#test2').show();
long_synchronous_function_call()
$('#test2').hide();
$('#test1').show();
}
function long_synchronous_function_call() {
$('#test1').html('<p>Some other data</p>');
var date = new Date();
while ((new Date()) - date <= 5000) {}
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div id="test1">
<p>Some data</p>
</div>
<div id="test2" style="display:none">
<p>Loading...</p>
</div>
<button onclick="run_test()">Call a long synchronous function!</button>Run Code Online (Sandbox Code Playgroud)
实际上,"加载"元素永远不会出现,而"其他一些数据"只是在没有我们假设的用户在漫长的等待期间得到任何反馈的情况下被替换.
我能做些什么来确保jQuery 现在隐藏并显示我的元素,而不是一旦我的所有函数都执行完毕?
在代码停止执行之前,屏幕不会呈现.这几乎总是所需的行为,因为它可以防止DOM处于不一致状态.
假设您确实需要运行一个长同步任务,并且您可以修复它或将其推迟给webworker,那么解决方案是使用setTimeout:
function run_test() {
$('#test1').hide();
$('#test2').show();
setTimeout(function(){
long_synchronous_function_call()
$('#test2').hide();
$('#test1').show();
},0);
}
function long_synchronous_function_call() {
$('#test1').html('<p>Some other data</p>');
var date = new Date();
while ((new Date()) - date <= 5000) {}
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div id="test1">
<p>Some data</p>
</div>
<div id="test2" style="display:none">
<p>Loading...</p>
</div>
<button onclick="run_test()">Call a long synchronous function!</button>Run Code Online (Sandbox Code Playgroud)
只是为了确保我没有帮你隐藏一个bug:永远不要做同步ajax调用.
这是合理的,做什么,我建议当你真的有一个合法的,有点长同步运行在浏览器中发生的事情,但(例如计算或复杂的GUI的建筑).
| 归档时间: |
|
| 查看次数: |
3414 次 |
| 最近记录: |