我创建了一个简单的Jquery表。它按字母排序,但不按数字排序。我不知道问题出在哪里。看看我的代码。
`
<!-- Font Awesome 4.7.0 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.ceo th,
.ceo td {
padding: 10px 30px;
}
.ceo th {
background: #333;
color: white;
}
.ceo th::after {
content: "\f0dc";
font-family: FontAwesome;
font-size: 12px;
color: #ccc;
margin-left: 8px;
}
.ceo th.asc:after {
display: inline-block;
content: " \f0de";
font-family: FontAwesome;
color: #fff;
}
.ceo th.desc:after {
display: inline-block;
content: " \f0dd";
font-family: FontAwesome;
color: #fff;
}
.ceo td {
background: #ccc;
}
</style>
<table class="ceo">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Marissa Mayer</td>
<td>3.3</td>
</tr>
<tr>
<td>Larry Page</td>
<td>-2</td>
</tr>
<tr>
<td>Oli Page</td>
<td>-13</td>
</tr>
<tr>
<td>Uniors</td>
<td>-14</td>
</tr>
<tr>
<td>Brown</td>
<td>22</td>
</tr>
<tr>
<td>Mark Zuckerberg</td>
<td>0</td>
</tr>
</tbody>
</table>
<script>
$(function () {
$('table').
on('click', 'th', function () {
var index = $(this).index(),
rows = [],
thClass = $(this).hasClass('asc') ? 'desc' : 'asc';
$('.ceo th').removeClass('asc desc');
$(this).addClass(thClass);
$('.ceo tbody tr').each(function (index, row) {
rows.push($(row).detach());
});
rows.sort(function (a, b) {
var aValue = $(a).find('td').eq(index).text(),
bValue = $(b).find('td').eq(index).text();
return aValue > bValue ?
1 :
aValue < bValue ?
-1 :
0;
});
if ($(this).hasClass('desc')) {
rows.reverse();
}
$.each(rows, function (index, row) {
$('.ceo tbody').append(row);
});
});
});
</script>
'我不知道问题出在哪里。第一列工作正常,但第二列的排序不正确。有人能告诉我为什么它不能排序吗?
Jquery表未按数字排序。
1条答案
按热度按时间plicqrtu1#
The issue is that you are taking the values as string.
instead you need to parse it to a number before doing the comparison.