Javascript 根据标题更改表格单元格的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27311908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:00:20  来源:igfitidea点击:

Change background color of table cells according to their header

javascripthtmlcsshtml-tablesharepoint-apps

提问by Laureant

I am dynamically constructing a calendar(html table) in javascript. I want to have the Saturday and Sunday columns with a gray background color.

我正在 javascript 中动态构建日历(html 表)。我想要带有灰色背景颜色的周六和周日列。

When I'm adding the other cells to the calendar, I want to check for the cells column header, check it's inner html text/class/id and color the cell if it's on a weekend.

当我将其他单元格添加到日历时,我想检查单元格列标题,检查它的内部 html text/class/id 并在周末为单元格着色。

This is where I add the column headers with the starting letters of the days :

这是我添加带有日期起始字母的列标题的地方:

<th bgcolor='#c1c1c1' width=20>S</th>" 
<th width=20>M</th>" 
<th width=20>T</th>" 
<th width=20>W</th>" 
<th width=20>T</th>" 
<th width=20>F</th>" 
<th bgcolor='#c1c1c1' width=20>S</th>" 

I tried this code, but it's not working properly...

我试过这段代码,但它不能正常工作......

var table = document.getElementById("calendarTable");
var rows = table.getElementsByTagName("tr");
for (var z = 0; z < rows.length-1; z++) {
    for (var y = 0; y < rows[z].cells.length; y++) {
        if(rows[z].cells[y].headers=="S")
            rows[z].cells[y].style.backgroundColor = "#c1c1c1";
    }
}

So what I would like to achieve is just a little code snippet, that goes through a whole tableelement, and checks every cells header for it's innerhtml content or id and changes it's background color accordingly.

所以我想要实现的只是一小段代码片段,它遍历整个表格元素,并检查每个单元格标题的 innerhtml 内容或 id 并相应地更改它的背景颜色。

Later Edit :

后来编辑:

Screenshot of the table :

表格截图:

enter image description here

在此处输入图片说明

The thing is, that the table is constructed according to the month we are currently in, and we don't necessarily know the index of Saturday or Sunday. (in the picture, the 1st of December lands on Monday, so this is a pretty lucky situation)

问题是,该表是根据我们当前所在的月份构建的,我们不一定知道星期六或星期日的索引。(图中12月1日是星期一,所以这是一个非常幸运的情况)

The Saturdays and Sundays are not fixed in the table. The calendar starts with the 1st of the current month and then gets the day for it. I know it's a little odd, but this is how it was designed by somebody else, and I have to work with it.

周六和周日在表中不固定。日历从当月的第一天开始,然后获取它的日期。我知道这有点奇怪,但这就是其他人设计的方式,我必须使用它。

The blue bars are marking a time interval, but that thing is already working.

蓝条标记了一个时间间隔,但那个东西已经在起作用了。

The code where I'm constructing the whole table would be really long to make it understandable.

我构建整个表格的代码会很长,以使其易于理解。

采纳答案by Pete

try this:

尝试这个:

for (var z = 1; z < rows.length; z++) {
       rows[z].cells[0].style.backgroundColor = "#c1c1c1"; // Sunday
       rows[z].cells[6].style.backgroundColor = "#c1c1c1"; // Saturday
}

Example

例子

Note your loop was finishing a row early and should start from 1 (as 0 will be your header row)

请注意,您的循环提前完成了一行,应该从 1 开始(因为 0 将是您的标题行)

UPDATE

更新

Given your edit I have mocked up a similar table and think the following js should solve your problem:

鉴于您的编辑,我模拟了一个类似的表格,并认为以下 js 应该可以解决您的问题:

for (var z = 3; z < rows.length; z++) {
    for (var a = 1; a < rows[z].cells.length; a++) {
        if (rows[2].cells[a - 1].innerHTML == "S") {
            rows[z].cells[a].style.backgroundColor = "#c1c1c1";
        }
    }
}

I have added comments to the fiddle example

我在小提琴示例中添加了注释

This code is slightly better on performance as you wouldn't need to loop through as many cells:

此代码在性能上稍好一些,因为您不需要循环遍历尽可能多的单元格:

var table = document.getElementById("calendarTable");
var rows = table.getElementsByTagName("tr");
var cellIndexes = [];

for (var a = 0; a < rows[2].cells.length; a++) {
    if (rows[2].cells[a].innerHTML == "S") {
        cellIndexes.push(a + 1); 
    }
}

for (var z = 3; z < rows.length; z++) {
    for (var i = 0; i < cellIndexes.length; i++) {
        rows[z].cells[cellIndexes[i]].style.backgroundColor = "#c1c1c1";
    }
}

Example

例子

回答by Sampson

I definitely wouldn't encourage you to use JavaScript for the styling. Instead, use as much CSS as you possibly can to keep performance high and script-dependency low.

我绝对不会鼓励您使用 JavaScript 进行样式设置。相反,尽可能多地使用 CSS 以保持高性能和低脚本依赖性。

I'll assume your table structure looks like the following. I tried my best to recreate from your screenshot:

我假设您的表结构如下所示。我尽力从您的屏幕截图中重新创建:

<table data-start-day="sun">
    <thead>
        <tr>
            <th>Year</th>
        </tr>
        <tr>
            <th rowspan="2">Month</th>
            <th>1</th><!-- fill in --><th>31</th>
        </tr>
        <tr>
            <th>S</th><th>M</th><!-- fill in -->
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Employee</td>
            <td></td><!-- x days in month -->
        </tr>
        <tr>
            <td>Exceptions</td>
            <td></td><!-- x days in month -->
        </tr>
    </tbody>
</table>

Next we'll use a series of compound selectors that are supported in IE 9 and up. Note the primary power is through the use of :nth-of-type, with which we can target the Sat/Sun columns no matter where they fall on the calendar itself:

接下来,我们将使用IE 9 及更高版本支持的一系列复合选择器。请注意,主要功能是通过使用:nth-of-type,我们可以使用它来定位 Sat/Sun 列,无论它们位于日历本身的哪个位置:

table[data-start-day=sat] thead tr:last-child th:nth-of-type(7n-13),
table[data-start-day=sat] thead tr:last-child th:nth-of-type(7n-12),
table[data-start-day=sat] tbody tr:nth-of-type(2n) :nth-of-type(7n-12):not(:first-child),
table[data-start-day=sat] tbody tr:nth-of-type(2n) :nth-of-type(7n-11):not(:first-child),
table[data-start-day=fri] thead tr:last-child th:nth-of-type(7n-12),
table[data-start-day=fri] thead tr:last-child th:nth-of-type(7n-11),
table[data-start-day=fri] tbody tr:nth-of-type(2n) :nth-of-type(7n-11):not(:first-child),
table[data-start-day=fri] tbody tr:nth-of-type(2n) :nth-of-type(7n-10):not(:first-child),
table[data-start-day=thu] thead tr:last-child th:nth-of-type(7n-11),
table[data-start-day=thu] thead tr:last-child th:nth-of-type(7n-10),
table[data-start-day=thu] tbody tr:nth-of-type(2n) :nth-of-type(7n-10):not(:first-child),
table[data-start-day=thu] tbody tr:nth-of-type(2n) :nth-of-type(7n-9):not(:first-child),
table[data-start-day=wed] thead tr:last-child th:nth-of-type(7n-10),
table[data-start-day=wed] thead tr:last-child th:nth-of-type(7n-9),
table[data-start-day=wed] tbody tr:nth-of-type(2n) :nth-of-type(7n-9):not(:first-child),
table[data-start-day=wed] tbody tr:nth-of-type(2n) :nth-of-type(7n-8):not(:first-child),
table[data-start-day=tue] thead tr:last-child th:nth-of-type(7n-9),
table[data-start-day=tue] thead tr:last-child th:nth-of-type(7n-8),
table[data-start-day=tue] tbody tr:nth-of-type(2n) :nth-of-type(7n-8):not(:first-child),
table[data-start-day=tue] tbody tr:nth-of-type(2n) :nth-of-type(7n-7):not(:first-child),
table[data-start-day=mon] thead tr:last-child th:nth-of-type(7n-8),
table[data-start-day=mon] thead tr:last-child th:nth-of-type(7n-7),
table[data-start-day=mon] tbody tr:nth-of-type(2n) :nth-of-type(7n-7):not(:first-child),
table[data-start-day=mon] tbody tr:nth-of-type(2n) :nth-of-type(7n-6):not(:first-child),
table[data-start-day=sun] thead tr:last-child th:nth-of-type(7n-7),
table[data-start-day=sun] thead tr:last-child th:nth-of-type(7n-6),
table[data-start-day=sun] tbody tr:nth-of-type(2n) :nth-of-type(7n-6):not(:first-child),
table[data-start-day=sun] tbody tr:nth-of-type(2n) :nth-of-type(7n-5):not(:first-child){
    background:#CCC;
}

The results match your desired output:

结果与您想要的输出相匹配:

enter image description here

在此处输入图片说明

Fiddle: http://jsfiddle.net/80fajvd6/4/

小提琴:http: //jsfiddle.net/80fajvd6/4/

回答by toto21

With Jquery :

使用 Jquery :

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>

<style type="text/css">
#calendarTable th {width: 20px}

</style>    
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


<table id="calendarTable">
<th>S</th>
<th>M</th> 
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
</table>

<script type="text/javascript">

$( "th:contains('S')" ).css( "background-color", "#c1c1c1" );



</script>
</body>
</html>