表中使用jQuery的升序和降序
问题描述:
使用jQuery的表中升序和降序,这里是JavaScript文件。错误是:表中使用jQuery的升序和降序
无法读取属性“localeCompare”的未定义
请帮我解决这个升序和降序排列。
function sortTable1() {
$('th').click(function() {
var table = $(this).parents('table').eq(0)
var rows = table.find("tr:not(:has('th'))").toArray().sort(comparer($(this).index()))
this.asc = !this.asc
if (!this.asc) { rows = rows.reverse() }
for (var i = 0; i < rows.length; i++) { table.append(rows[i]) }
})
function comparer(index) {
return function (a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
}
function getCellValue(row, index) { return $(row).children('td').eq(index).html() }
// additional code to apply a filter
$('table').each(function() {
var table = $(this)
var headers = table.find('th').length
var filterrow = $('<tr>').insertAfter($(this).find('th:last()').parent())
for (var i = 0; i < headers; i++) {
filterrow.append($('<th>').append($('<input>').attr('type', 'text').keyup(function() {
table.find('tr').show()
filterrow.find('input[type=text]').each(function() {
var index = $(this).parent().index() + 1
var filter = $(this).val() != ''
$(this).toggleClass('filtered', filter)
if (filter) {
var el = 'td:nth-child(' + index + ')'
var criteria = ":contains('" + $(this).val() + "')"
table.find(el + ':not(' + criteria + ')').parent().hide()
}
})
})))
}
filterrow.append($('<th>').append($('<input>').attr('type', 'button').val('Clear Filter').click(function() {
$(this).parent().parent().find('input[type=text]').val('').toggleClass('filtered', false)
table.find('tr').show()
})))
})
}
这里是表结构:
<table id="test" class="master_table test_1 table no-border hover">
<thead class="no-border">
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th class="sortable1">Name</th>
<th class="text-center">Status</th>
<th>Date</th>
<th id="nm" class="text-center">Hrs</th>
</tr>
</thead>
</table>
答
你应该检查空值
return function (a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
if(valA != null && valB!=null)
{
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
else{
return 0;
}
}
喜公园,它现在的工作,但我的表包含月份明智的排序。我需要1月01日,1月23日,2月9日,2月11日,现在我正在按字母顺序排列。请帮我解决这个问题。 – White