首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用JavaScript动态创建表的条件格式

用JavaScript动态创建表的条件格式
EN

Stack Overflow用户
提问于 2021-02-11 16:05:10
回答 1查看 53关注 0票数 0

我的代码从数据库中读取记录,并在动态创建的表中显示记录。效果很好。但条件格式不按预期工作。例如,如果单元格值为"hello",则单元格背景变为绿色。但是只有第一个单元格变成绿色,并且单元格值不是"hello“。会有什么问题?

代码语言:javascript
复制
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";
  }
}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-11 16:28:05

在当前的实现中,您的代码只适用于一个等于"hello“的单词,而这是的第一个单词。document.getElementbyID将返回它找到的id的第一个元素。

考虑到这一点:

代码语言:javascript
复制
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,有条件地给它一个样式,然后将它添加到表中,如下所示:

代码语言:javascript
复制
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);
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66158285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档