动态比较TD值并设置排名



td中的值是从PHP生成的,现在需要比较这些值并根据值设置排名,例如('1,2,3...'(,使用jquery动态。例如,我在以下代码片段中为最大值设置了静态排名1。但是我无法弄清楚 - 如何通过jquery动态循环和设置排名

$(document).ready(function(){
var high = Math.max.apply(Math, $('.rank').map(function(){
return $(this).text()
}))
$('.rank').each(function(){
var mark = $(this).text();
if(mark == high){ 
$(this).find('span#rank').text(' (1)');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<table>
<tr>
<th>Student</th>
<th>Total</th>
</tr>
<tr>
<td>John</td>
<td class='rank'>20<span id='rank'></span></td>
</tr>
<tr>
<td>Jack</td>
<td class='rank'>40<span id='rank'></span></td>
</tr>
<!-- Multiple Tr are here, generated from php -->
</table>
</body>
</html>

首先id文档中必须是唯一的。要获得排名:

  1. 获取所有等级并将它们存储在数组中
  2. 按升序对此数组进行排序
  3. .rank上重新迭代并获取上一个数组中当前排名的索引
  4. 这将是你的绝对排名。

let allRanks = [];
$('.rank').each(function(){
allRanks.push( +$(this).text() );
})
allRanks.sort();
$(".rank").each(function(){
let rankVal = +$(this).text();
let rank = allRanks.indexOf(rankVal)+1;
$(this).find(".innerrank").html(" ("+rank+")")

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<table>
<tr>
<th>Student</th>
<th>Total</th>
</tr>
<tr>
<td>John</td>
<td class='rank'>20<span class='innerrank'></span></td>
</tr>
<tr>
<td>Jack</td>
<td class='rank'>40<span class='innerrank'></span></td>
</tr>
<tr>
<td>Jack</td>
<td class='rank'>30<span class='innerrank'></span></td>
</tr>
<!-- Multiple Tr are here, generated from php -->
</table>
</body>
</html>

PS:您可能需要处理多个排名值相同的情况。

您可以在排名div 中创建一个包含数字的数组,然后对其进行排序和迭代。 迭代时,找到包含数字的排名div,并将排名作为索引 + 1。

请参阅下面的代码

$(document).ready(function(){
var arr = new Array();
$('.rank').each(function(){
arr.push($(this).text());
});
arr.sort();
$.each(arr, function( index, value ) {
$('.rank:contains(' + value + ')').find('span.rankNumber').html(index+1);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<table>
<tr>
<th>Student</th>
<th>Total</th>
</tr>
<tr>
<td>John</td>
<td class='rank'>20<span class='rankNumber'></span></td>
</tr>
<tr>
<td>Jack</td>
<td class='rank'>40<span class='rankNumber'></span></td>
</tr>
<!-- Multiple Tr are here, generated from php -->
</table>
</body>
</html>

最新更新