我想突出显示每行中最高的数字。我想使用css类.max
。但我需要避免在第1列和第1行搜索,也要省略空单元格。
table,
th,
td {
border: 1px solid black;
}
table {
border-collapse: collapse;
width: 100%;
}
tr:nth-child(even) {
background-color: #e5e5e5;
}
.max {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>ITEMS</th>
<th>SHOP1</th>
<th>SHOP2</th>
<th>SHOP3</th>
</tr>
<tr>
<th>ITEM1</th>
<th>2</th>
<th>1,333333</th>
<th>1,5</th>
</tr>
<tr>
<th>ITEM2</th>
<th>6</th>
<th>5</th>
<th>4</th>
</tr>
<tr>
<th>ITEM3</th>
<th>4</th>
<th>30</th>
<th>20</th>
</tr>
</table>
为了完成这项工作,您可以循环遍历每一行并在单元格中创建值的数组,并随时将它们转换为浮点数。然后,您可以使用reduce()
获取具有最高值的单元格的索引并将类添加到其中。
请注意,我稍微修改了HTML以便更容易地选择相关单元格。即分别使用thead
和tbody
分隔标题单元格和正文,并将我们想要定位的单元格更改为td
而不是th
。试试这个:
$('tbody tr').each(function() {
var $tds = $(this).find('td');
var values = $tds.map(function() {
return parseFloat($(this).text().trim().replace(',', '.'));
}).get();
$tds.eq(values.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0)).addClass('max');
});
table,
th,
td {
border: 1px solid black;
}
table {
border-collapse: collapse;
width: 100%;
}
tr:nth-child(even) {
background-color: #e5e5e5;
}
.max {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>ITEMS</th>
<th>SHOP1</th>
<th>SHOP2</th>
<th>SHOP3</th>
</tr>
</thead>
<tbody>
<tr>
<th>ITEM1</th>
<td>2</td>
<td>1,333333</td>
<td>1,5</td>
</tr>
<tr>
<th>ITEM2</th>
<td>6</td>
<td>5</td>
<td>4</td>
</tr>
<tr>
<th>ITEM3</th>
<td>4</td>
<td>30</td>
<td>20</td>
</tr>
</tbody>
</table>