我有一个用于一些计算的表格,如果传递了单元格值,我想以某种颜色显示表格的该列。 我现在有这个:
<script type="text/javascript">
$(document).ready(function(){
$('#myTable td.y_n').each(function(){
if ($(this).text() < 0.4) {
$(this).css('background-color','#a9edb8');
}
else {
$(this).css('background-color','#eda9ca');
}
});
});
</script>
但这仅适用于单元格。
有什么想法吗?谢谢!
最佳答案
如果我正确理解您的目标,您希望设置整个列的背景颜色(如果y_n
单元格包含数值)并根据该值选择颜色。
要设置整个列,您可以获取相应索引处的表格单元格,但更简单的是使用列组:
$(document).ready(function(){
var cols = $('#myTable col'); //get the column groups
$('#myTable td.y_n').each(function(){
var text = this.innerText; //text of the td
if(text.length > 0 && !isNaN(this.innerText)){ //check if it's a number
var ind = $(this).index(); //the index of the td inside its tr = the column index
$(cols[ind]).css('background-color', parseFloat(text) < 0.4 ? '#a9edb8' : '#eda9ca'); //set the col of the column group
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<colgroup>
<col>
<col>
<col>
</colgroup>
<tr>
<td>r1</td>
<td class='y_n'></td>
<td class='y_n'>.7</td>
</tr>
<tr>
<td>r2</td>
<td class='y_n'>.1</td>
<td class='y_n'>.6</td>
</tr>
<tr>
<td>r3</td>
<td>a</td>
<td>b</td>
</tr>
</table>
关于javascript - 如果单元格中的值传递给 JavaScript,则以颜色显示表格的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41097047/