У меня есть таблица:
<table>
<tr>
<th>Name</th>
<th>Id</th>
<th>Value</th>
</tr>
<tr>
<td>Ankaran</td>
<td>101</td>
<td>91</td>
</tr>
<tr>
<td>Ljubljana</td>
<td>102</td>
<td>213</td>
</tr>
<tr>
<td>Celje</td>
<td>103</td>
<td>711</td>
</tr>
<tr>
<td>Portorož</td>
<td>104</td>
<td>121</td>
</tr>
</table>
Я хочу получить два самых низких значения из последнего столбца ("Значение") и покрасить теги td этими двумя значениями. Какой код может это сделать?
Я попробовал это:
$(document).ready(function(){
$("#btnSelect").click(function(e) {
e.preventDefault();
var values= new Array();
$('tr').each(function () {
var sorted = $(this).find('td:last').html();
values.push(sorted);
});
console.log(values);
});
});
Я получил самое низкое значение, но это примерно так, как я понял, и я не думаю, что это надежное решение
Прежде всего, проверьте Fiddle Demo
Рассмотрим ваш HTML, вот мое решение css & js:
Javascript
var tds = $('td.value');
var arr = $.makeArray(tds);
arr.sort(function(a,b){
return parseInt($(b).text()) - parseInt($(a).text());
});
$(arr[arr.length-2]).addClass('lowest');
$(arr[arr.length-1]).addClass('lowest');
CSS
td.lowest {background-color:lightgreen;}
var ok = $('table tr td:last-child').map(function () {
return $(this).text();
}).get().sort(function (x, y) {
return x - y
});
alert(ok[0] + ' - is the smallest');
alert(ok[1] + ' - is the 2nd smallest');
Это должно сделать трюк: -
var values = $('td:last-child').sort(function(a, b) {
return $(a).text() - $(b).text();
}).slice(0, 2).css('color', 'red').map(function() {
return $(this).text();
}).get();
Итак, сортируйте каждый td:last-child
по его значению text()
(от низкого до высокого), затем используйте slice()
чтобы получить первые два элемента. Примените css()
к этим элементам, затем используйте map()
чтобы вернуть их text()
, который будет присвоен var values
var values = [],
tds = $("table tr").find("td:last");
tds.each(function(){
$(this).data("val",$(this).text());
values.push(parseInt($(this).text()))
})
values.sort(function(x,y){return x > y});
tds.each(function(){
if($(this).data("val") == values[0] || $(this).data("val") == values[1])
$(this).css("color","red");
})
значения [0] и значения [1] будут наименьшими и вторыми наименьшими значениями соответственно.
Пытаться
var map = {}, array = [];
var $tds = $('table tr').slice(1).find('td:last-child').each(function () {
var value = +$(this).text();
if (map[value]) {
map[value].push(this);
} else {
map[value] = [this];
array.push(value);
}
})
array.sort(function(a1, a2){
return a1 - a2;
});
$tds.filter(function () {
return $.inArray(+$(this).text(), array) < 2;
}).css('color', 'red')
Демо: скрипка
Хорошо, я бы пошел с функцией сортировки на спине, а затем .filter
функцию .filter
из ответа Аруна или просто
$(this).attr('style', 'color:red;')
или любой цвет, который вы хотите, выделить ячейку, или если вы хотите выделить всю строку, которую вы могли бы просто пойти
$(this).parent().attr('style', 'color:red;')