当您点击表格标题旁边的小按钮时,我正尝试在升序和降序订单中对表格进行排序。
它应该按字母顺序排序,并按日期排序。
任何指针都将不胜感激!
以下是我的代码
var table = $(".main").append("<table></table>");
var thead = '<thead><tr></tr></thead>';
table.append(thead);
var header = [{
title: 'Name',
sortBy: 'name'
}, {
title: 'Last Name',
sortBy: 'lastName'
}, {
title: 'Date of birth',
sortBy: 'dob'
}].map(
function(header) {
var sortButton = '<button id="' + header.sortBy + '" onclick=sortRows("' + header.sortBy + '")>/\\</button>';
$('thead').append('<th>' + header.title + ' ' + sortButton + '</th>');
}
)
var tbody = "<tbody></tbody>";
var data = [{
name: 'Peter',
lastName: 'Petterson',
dob: '13/12/1988'
}, {
name: 'Anna',
lastName: 'Jones',
dob: '06/02/1968'
}, {
name: 'John',
lastName: 'Milton',
dob: '01/06/2000'
}, {
name: 'James',
lastName: 'White',
dob: '30/11/1970'
}, {
name: 'Luke',
lastName: 'Brown',
dob: '15/08/1999'
}];
$('.search').change(function(event) {
searchedName = event.target.value;
})
table.append(tbody);
draw();
function draw() {
$('tbody').html('');
data.map(
function(row, i) {
$('tbody').append(
'<tr><td>' + row.name +
'</td><td>' + row.lastName +
'</td><td>' + row.dob +
'</td><td><button onclick=editRow(' + i + ')>edit</button><button onclick=delRow(' + i + ') >delete</button></td></tr>'
)
}
)
}
var editRow = function(rowNumber) {
var editableRow = "<td><input id='name'/></td><td><input id='lastName'/></td><td><input id='dob' type='date'/></td><td><button onclick=saveRow(" + rowNumber + ")>save</button></td>";
var name = $('tbody > tr:nth-child(' + (rowNumber + 1) + ') > td:first-child').text();
var lastName = $('tbody > tr:nth-child(' + (rowNumber + 1) + ') > td:nth-child(2)').text();
var dob = $('tbody > tr:nth-child(' + (rowNumber + 1) + ') > td:nth-child(3)').text();
$('tbody > tr:nth-child(' + (rowNumber + 1) + ')').html(editableRow);
$('tbody > tr:nth-child(' + (rowNumber + 1) + ') > td:first-child > input').val(name);
$('tbody > tr:nth-child(' + (rowNumber + 1) + ') > td:nth-child(2) > input').val(lastName);
$('tbody > tr:nth-child(' + (rowNumber + 1) + ') > td:nth-child(3) > input').val(dob);
}
var sortRows = function(sortBy) {
isAscending[sortBy] = !isAscending[sortBy];
$('#' + sortBy).text(isAscending[sortBy] ? '\\/' : '/\\');
};
var delRow = function(num) {
data.splice(num, 1);
draw();
}
var addPerson = function() {
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
}
var saveRow = function(num) {
data[num].name = $('#name').val();
data[num].lastName = $('#lastName').val()
data[num].dob = $('#dob').val();
draw();
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="main"></div>
&#13;