I'd like some help with the following jQuery code if possible...
$(document).ready(function() {
$('table.sortable').each(function() {
var $table = $(this);
$('th', $table).each(function(column) { // #A
var $header = $(this);
$header.click(function() {
var rows = $table.find('tbody > tr').get();
rows.sort(function(a, b) { // #B
var keyA = $(a).children('td').eq(column).text().toUpperCase(); //#C
var keyB = $(b).children('td').eq(column).text().toUpperCase();
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
$.each(rows, function(index, row) { //#D
$table.children('tbody').append(row);
});
});
});
});
});
For the comments I've added (#A through to #D), can somebody explain to me:
#A - What signifies the closure/end of this function... i.e. where does the function end? I'm naively looking for a closing curly brace, otherwise from reading the code I'm assuming the whole body of code is run for each 'th' element encountered, which doesn't seem very efficient? Does one of the "});"'s at the end signify the end of this function?
#B - I would love to understand how this comparator function works. My book covers it really briefly and I can't find any other resources on the web! What values will be passed into the function via the arguments 'a' and 'b'? Can somebody painstakingly explain this whole function, please?! :)
#C - How does the .eq(column) part work? I would assume that if 'column' contains the iteration the loop is currently on, the value will always be the final iteration value? Or does this comparator function run for each iteration through the .each loop?
#D - This function presumably goes through each row of the sorted array rows and appends it to the table body. Are these two arguments (index, row) always included in the $.each callback function?
Any help gratefully received!! I already have an answer for #B, if you could just help by answering one of the queries, I will show my appreciation with upvotes! Thanks in advance.