我有一个由JSON创建的HTML表。这张表是一所大学校长的地图,它列出了您所学专业的所有必修课程。我希望课程的单元格颜色取决于状态。例如,绿色表示课程已完成,黄色表示正在进行中,红色表示需要采取。下面是列,以及createtablefromJSON函数
var col2 = ["year","term","major1","major2","major3","major4","major5","core1","Core2","Credits"] ;
function CreateTableFromJSON() {
var myCourses = <?php echo $test1; ?> ;
var col = [] ;// EXTRACT VALUE FOR HTML HEADER.
var col2 = ["year","term","major1","major2","major3","major4","major5","core1","Core2","Credits"] ;
for (var i = 0; i < myCourses.length; i++) {
for (var key in myCourses[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table"); // CREATE DYNAMIC TABLE.
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col2.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col2[i];
tr.appendChild(th);
}
我的问题是如何根据课程状态更改单元格的颜色
for (var i = 0; i < myCourses.length; i++) {
tr = table.insertRow(-1); // ADD JSON DATA TO THE TABLE AS ROWS.
for (var j = 0; j < col2.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myCourses[i][col[j]];
if (<?php in_array ?> (myCourses[i][col[j]] <?php echo ",". json_encode($done_course) ?> ) {
<?php if ($done) { ?> tabCell.className = 'success'; <?php } ?> }
if (<?php in_array ?> (myCourses[i][col[j]] <?php echo ",". json_encode($pending_course) ?> ) {
<?php if ($pending) { ?> tabCell.className = 'pending'; <?php } ?> }
}
if (<?php in_array ?> (myCourses[i][col[j]] <?php echo ",". json_encode($progess_course) ?> ) {
<?php if ($progess) { ?> tabCell.className = 'inprocess'; <?php } ?> }
}
}
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
答案 0 :(得分:0)
您必须像这样检查数组中的
indexOf()
if (myCourses[i][col[j]] == "<?php echo $done_course; ?>") {
<?php if ($done) { ?> tabCell.className = 'success'; <?php } ?>
}
else if (myCourses[i][col[j]] == "<?php echo $pending_course; ?>") {
<?php if ($pending) { ?> tabCell.className = 'pending'; <?php } ?> }
}
else {
<?php if ($progess) { ?> tabCell.className = 'inprocess'; <?php } ?> }
}
答案 1 :(得分:0)
将php数组转换为js数组。然后使用.includes()函数进行检查
for (var i = 0; i < myCourses.length; i++) {
tr = table.insertRow(-1); // ADD JSON DATA TO THE TABLE AS ROWS.
for (var j = 0; j < col2.length; j++) {
var tabCell = tr.insertCell(-1);
var done_course = <?php echo json_encode($done_course); ?> ;
var pending_course = <?php echo json_encode($pending_course); ?> ;
var progress_course = <?php echo json_encode($progress_course); ?> ;
tabCell.innerHTML = myCourses[i][col[j]];
if (done_course.includes(myCourses[i][col[j]])) {
tabCell.className = 'success';
} else if (pending_course.includes(myCourses[i][col[j]])) {
tabCell.className = 'completed'; }
else {
tabCell.className = 'inprocess'; }
}
}