【发布时间】:2019-05-30 14:43:49
【问题描述】:
我有一个带有 JSON 数据的 HTML 表,我在 UI 上部分呈现。
我在做什么
- 我通过
ajax一次调用完整数据,然后将数据分成 12-12 行,因为按照我的要求,一页最多可以有 12 行 - 我每 3 秒刷新一次
div,一次显示 12-12 行 - 当页面出现时,我显示前 12 行,然后在 3 秒后隐藏前 12 行并显示下 12 行
- 这就是我的工作方式
我正在努力实现的目标
加载完整数据后,页面显示空白,不符合要求
我正在尝试在加载完整数据后再次调用
ajax
工作代码
$(document).ready(function() {
myFun();
function myFun() {
$.ajax({
async: true,
url: "MenuDisplay",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(tableValue) {
addTable(tableValue)
window.setInterval(showRows, 3000);
showRows();
}
});
}
function showRows() {
// Any TRs that are not hidden and not already shown get "already-shown" applies
if ($(".hidden:lt(12)").length > 0) {
$("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
} else {
$("tr:not(.hidden):not(.already-shown)").addClass("already-shown"); // this one is also calling after 3 seconds after last page i want to call this imidiatly
$.ajax({
async: true,
url: "MenuDisplay",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(tableValue) {
addTable(tableValue)
}
});
}
$(".hidden:lt(12)").removeClass("hidden"); // this one is to hide previous rows and show next
}
function addTable(tableValue) {
var $tbl = $("<table />", {
"class": "table fixed"
}),
$tb = $("<tbody/>"),
$trh = $("<tr/>");
var split = Math.round(tableValue.length / 4);
for (i = 0; i < split; i++) {
$tr = $("<tr/>", {
class: "hidden "
});
for (j = 0; j < 4; j++) {
$.each(tableValue[split * j + i], function(key, value) {
if (typeof(value) === "number") {
$("<td/>", {
"class": "text-right color" + (j + 1)
}).html(value).appendTo($tr);
} else {
$("<td/>", {
"class": "text-left color" + (j + 1)
}).html(value).appendTo($tr);
}
});
}
$tr.appendTo($tb);
}
$tbl.append($tb);
$("#DisplayTable").html($tbl);
}
});
tbody>tr>td {
white-space: normal;
border-collapse: collapse;
font-family: Verdana;
font-weight: bold;
font-size: .9em;
}
td:nth-child(2),
td:nth-child(4),
td:nth-child(6),
td:nth-child(8) {
width: 85px;
max-width: 85px;
height: 63px
}
.fixed {
table-layout: fixed;
}
.color1 {
background: #4AD184;
}
.color2 {
background: #EA69EF;
}
.color3 {
background: #E1A558;
}
.color4 {
background: #F4F065;
}
.hidden,
.already-shown {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div id="DisplayTable"></div>
检查 This fiddle 以获取 JSON 数据的工作示例
【问题讨论】:
-
使用setInterval每3秒调用一次
myFun() -
但每 3 秒我调用一次 showRows(),一旦它完成然后我想运行 myFun()
-
showRows()不会更改您的数据/结果,因为您从myFunc()获取数据。您必须添加一个标志来检查所有数据是否已加载。 -
@NgocNam 我的数据只加载一次,每当页面加载时,我会每 3 秒显示一次完整数据中的数据,并使用 css 隐藏和显示
-
我明白了你的想法。试试这个格式:1.
loadDataIntoArray()。 2.showDataTable(array, index)。数组是您在第一个函数中加载的数据,然后是index=1; setInterval(function(){showDataTable(array, index); index+=12; }, 3000);
标签: javascript jquery html css