在HTML表中,我必须获取列的最大值,然后获取其在同一行的另一列中查找其他信息的位置。目前,我可以找到最大值,但不能找到它在列中的位置。
我有一个经典的表和代码如下:
<body>
<table id="tableau">
<thead>
<tr>
<th>#</th>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>José</td>
<td>Maire</td>
<td>Paris</td>
<td>1000</td>
</tr>
<tr>
<td>2</td>
<td>Lilianne</td>
<td>Maire</td>
<td>Paris</td>
<td>1234</td>
</tr>
<tr>
<td>3</td>
<td>Raymond</td>
<td>Fourbe</td>
<td>Bruxelles</td>
<td>123</td>
</tr>
<tr>
<td>4</td>
<td>Huguette</td>
<td>Fourbe</td>
<td>Bruxelles</td>
<td>129099</td>
</tr>
</tbody>
</table>
<button type="buttonmax" id="Score maximum" class="btn btn-info">Afficher le Score maximum</button>
<script>
var myArray = new Array();
$(document).ready(function()
{
$("#tableau tr td:nth-child(5)").each(function(i){
myArray.push($(this).text());
});
document.getElementById("Score maximum").onclick = function(){
var max = Math.max.apply(Math, $('td:nth-child(5)').map(function(i,elem){
return Number($(elem).text());
}));
alert(max);}
});
</script>
</body>
在我看来,我必须找到最大值的索引来显示实现此值的人的Firstname
和Lastname
,位于同一行但在其他列中。
你认为这是最好的方法吗?
我尝试了不同的代码来获得最大的索引但没有工作。
你能帮助我获得指数并找到实现最高分的人吗?
这将是实现这一目标的一种方法(尽管它不是非常高效,因为如果当前检查的值高于前一个值,它将覆盖整个对象)。请注意:我将您的ID更改为“scoremaximum”,因为您的id选择器中确实不应该有空格。
var max = {
score: 0,
id: 0,
firstname: '',
lastname: '',
city: ''
};
$("#tableau tr td:nth-child(5)").each(function(index, elem) {
var current = parseFloat($(elem).text());
if(current > max.score) {
max.score = current;
max.id = $("#tableau tr td:nth-child(1)")[index].textContent;
max.firstname = $("#tableau tr td:nth-child(2)")[index].textContent;
max.lastname = $("#tableau tr td:nth-child(3)")[index].textContent;
max.city = $("#tableau tr td:nth-child(4)")[index].textContent;
}
});
$('#scoremaximum').on('click', function() {
alert("score: " + max.score + ", id: " + max.id + ", firstname: " + max.firstname + ", lastname " + max.lastname + ", city: " + max.city);
});
如果要向对象添加另一个属性来跟踪循环外的索引并相应地更新为max.score,则可以稍微提高性能。然后你可以在循环完成后运行一个回调函数并将其传递给max.index。这看起来像这样:
var max = {
score: 0,
index: 0,
id: 0,
firstname: '',
lastname: '',
city: ''
};
$("#tableau tr td:nth-child(5)").each(function(index, elem) {
var current = parseFloat($(elem).text());
if(current > max.score) {
max.score = current;
max.index = index;
}
return callback(max.index);
});
function callback(index) {
max.id = $("#tableau tr td:nth-child(1)")[index].textContent;
max.firstname = $("#tableau tr td:nth-child(2)")[index].textContent;
max.lastname = $("#tableau tr td:nth-child(3)")[index].textContent;
max.city = $("#tableau tr td:nth-child(4)")[index].textContent;
}
$('#scoremaximum').on('click', function() {
alert("score: " + max.score + ", id: " + max.id + ", firstname: " + max.firstname + ", lastname " + max.lastname + ", city: " + max.city);
});