我的代码从数据库中读取记录,并在动态创建的表中显示记录。效果很好。但条件格式不按预期工作。例如,如果单元格值为"hello",则单元格背景变为绿色。但是只有第一个单元格变成绿色,并且单元格值不是"hello“。会有什么问题?
function dynamicTable() {
var tableRef = document.getElementById("id_table");
tableRef.insertRow().innerHTML = "<td id='id_word'>" + word + "</td>" + "<td id='id_count'>" + count + "</td>";
if (word == “hello“) {
document.getElementById("id_word").style.backgroundColor = "green";
}
}
发布于 2021-02-11 16:28:05
在当前的实现中,您的代码只适用于一个等于"hello“的单词,而这是的第一个单词。document.getElementbyID将返回它找到的id的第一个元素。
考虑到这一点:
function dynamicTable(word, count) {
var tableRef = document.getElementById("id_table");
tableRef.insertRow().innerHTML = "<td id='id_word'>" + word + "</td>" + "<td id='id_count'>" + count + "</td>";
if (word == "hello") {
document.getElementById("id_word").style.backgroundColor = "green";
}
}
let words = ["hello", "goodbye", "blah", "blah", "hello", "hello", "something"];
words.forEach((word, i) => {
dynamicTable(word, i);
});第一个带有word的单元格将有一个绿色的背景,但没有其他单元格。
也许您可以单独创建td,有条件地给它一个样式,然后将它添加到表中,如下所示:
function dynamicTable(word, count) {
var tableRef = document.getElementById("id_table");
const cell_word = document.createElement("td");
cell_word.id = "id_word";
cell_word.innerText = word;
if (word === "hello") {
cell_word.style.backgroundColor = "green";
}
const cell_count = document.createElement("td");
cell_count.id = "id_count";
cell_count.innerText = count;
tableRef.insertRow().append(cell_word, cell_count);
}
let words = ["hello", "goodbye", "blah", "blah", "hello", "hello", "something"];
words.forEach((word, i) => {
dynamicTable(word, i);
});https://stackoverflow.com/questions/66158285
复制相似问题