本文介绍了jQuery/JavaScript在表列中找到最高价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的桌子
<table id="aktivita">
<tr>
<td>Jack</td>
<td>450</td>
<td>794</td>
<td>784</td>
</tr>
<tr>
<td>Steve</td>
<td>145</td>
<td>794</td>
<td>789</td>
</tr>
<tr>
<td>Mike</td>
<td>2794</td>
<td>2794</td>
<td>79</td>
</tr>
</table>
如何获得第二列之后的每列(名称之后),并将最高值类别设置为高,将最低类别值设置为低?如果更多的td具有相同的值并且最高(或最低),则所有td必须具有适当的类别.
How can I get each column since the second (after the names) and set the highest value class high, the lowest value class low? If more td have same value and is highest (or lowest) all must have proper class.
$('#aktivita tr').each(function(){
var first = $(this).find("td:nth-of-type(2)").text();
var second = $(this).find("td:nth-of-type(3)").text();
var third = $(this).find("td:nth-of-type(4)").text();
console.log(first);
console.log(second);
console.log(third);
});
这是我还没有的.我不太喜欢即时消息用于基本上相同代码的变量.有什么方法可以使其干燥吗?
This is what I have yet. I don't like much that im using for variables basicly same code. Is there a way how to make it dry?
推荐答案
您可以遍历 td
s并找到min和max并进行相应处理
You can loop over td
s and find min and max and process accordingly
$(function(){
var cols = []
var trs = $('#aktivita tr')
var data =$.each(trs , function(index, tr){
$.each($(tr).find("td").not(":first"), function(index, td){
cols[index] = cols[index] || [];
cols[index].push($(td).text())
})
});
cols.forEach(function(col, index){
var max = Math.max.apply(null, col);
var min = Math.min.apply(null, col)
$('#aktivita tr').find('td:eq('+(index+1)+')').each(function(i, td){
$(td).toggleClass('max', +$(td).text() === max)
$(td).toggleClass('min', +$(td).text() === min)
})
})
})
.max {
color: blue
}
.min {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="aktivita">
<tr>
<td>Jack</td>
<td>450</td>
<td>794</td>
<td>784</td>
</tr>
<tr>
<td>Steve</td>
<td>145</td>
<td>794</td>
<td>789</td>
</tr>
<tr>
<td>Mike</td>
<td>2794</td>
<td>2794</td>
<td>79</td>
</tr>
</table>
这篇关于jQuery/JavaScript在表列中找到最高价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!