![](/img/trans.png)
[英]How to hide the later pages and show pagination in jquery ajax response?
[英]jQuery hide() and show() not immediately run when reversed later in the function
我正在使用jQuery的.show()
.hide()
和.show()
函数来显示加载消息,同时可能执行很长的同步Web服务调用。
单击下面片段中的按钮时,我希望文本“ Some data”将立即替换为“ Loading ...”,然后在5秒钟后返回“ Some other data”。
如您所见,这不会发生:
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) {} }
<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>
实际上,“ Loading”元素永远不会出现,“ Some other data”将被替换,而我们的假设用户在漫长的等待期间不会得到任何反馈。
我该怎么做才能确保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) {} }
<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>
只是为了确保我不会帮助您隐藏一个错误: 切勿进行同步ajax调用 。
这是合理的,做什么,我建议当你真的有一个合法的,有点长同步运行在浏览器中发生的事情,但(例如计算或复杂的GUI的建筑)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.