嗨,我有一个 JavaScript 函数,它获取 JSON 文件的内容并将其放入表格中,这是代码。
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<tbody>';
content += '<td>' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td>' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
content += '</tbody>';
content += '<p>';
$(content).appendTo("tbody");
console.log(Person);
});
});
但是我需要的是通过 if 语句进行一些格式化,例如
通常我会使用诸如一堆糟糕的 If 语句之类的东西。
if (Person.clock !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'lime';
}
if (Person.Off !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'red';
}
if (Person.on !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'lime';
}
if (Person.out !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'red';
}
但是,我正在努力寻找最好的方法,将我已有的功能与创建表的功能结合起来,并将 If 语句的格式放在一起 最好的方法是什么?
最佳答案
为什么不为每个这样的情况添加一个类。像这样的东西:
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<td>' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td class="'+(Person.clock? 'hasClock' : '') +'">' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
$(content).appendTo("tbody");
console.log(Person);
});
});
然后将一个类添加到您的 css 中:
.hasClock{
background-color :lime;
}
关于Javascript/jQuery 根据值更改表格的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25265012/