我有一个加载数据的页面(它将使用AJAX),所以我想显示一条“正在加载,请稍候”消息目前,我正在使用循环模拟网络延迟我使用JQuery来设置和显示消息,但直到循环完成后才显示消息我需要做什么来“刷新”jquery命令,以便在调用循环之前显示消息?
我在下面提供了基本的css、html和jquery/javascript。
<!DOCTYPE html>
<html>
<head>
<style>
.ais-card-message {
padding: 6px;
margin-top: 6px;
margin-bottom: 6px;
text-align: left;
}
.ais-card-message-info {
background-color: lightskyblue;
}
.ais-card-message-warn {
background-color: lightpink;
}
</style>
</head>
<body>
<div id="title">
<p>Message "Loading, please wait ..." should appear below when button clicked.
Followed by either "Error" or "Loaded" after a short delay.</p>
</div>
<div id="data">Data will be loaded here</div>
<div id="msgBox" class="ais-card-message">Messages should display here</div>
<div><button id="btnLoad">Load</button></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function showMsg(msg, type) {
// msg is message to display. type is either "info" or "warn"
$('#msgBox').removeClass("ais-card-message-info ais-card-message-warn");
$('#msgBox').addClass("ais-card-message-" + type);
$('#msgBox').text(msg);
$('#msgBox').show();
return
}
$('#btnLoad').click(function(){
// For some reason the following message doesn't display
showMsg('Loading, please wait ...', 'info');
if (!loadData()) {
// But this message does display if loadData returns false
showMsg('Error', 'warn');
return
}else{
// and this message also displays if loadData returns true
showMsg('Loaded', 'info');
return
}
});
function loadData() {
// Just a loop to simulate network delay
var i;
for (i=0; i < 100000; i++) {
var j;
for (j=0; j < 100000; j++) {
var k = Math.sqrt(j);
}
}
$('#data').text("Here is some dummy data");
return true
}
});
</script>
</body>
</html>