gpt4 book ai didi

javascript - 在 jQuery 中使用表中的升序和降序

转载 作者:行者123 更新时间:2023-11-28 05:58:11 26 4
gpt4 key购买 nike

在 jQuery 中使用表格的升序和降序,这里是 JavaScript 文件。错误是:

Cannot read property 'localeCompare' of undefined

请帮我解决这个升序和降序。

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;
}
}

关于javascript - 在 jQuery 中使用表中的升序和降序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36934810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com