Set backcolor of row based on a DATE in a cell exceeding another date
Given a table with a column "DueDate", what would be the approximate jQuery code for say, setting the backcolor of the table rows based on the value of each DueDate cell with respect to another date?
I am most specifically interested in the pitfalls involving how to properly handle the dates....how to c开发者_JS百科onsume a string value explicitly as a date in javascript, do I have to be very strict with the date formatting, etc.
Given that you are able to convert the dates to seconds (or milliseconds) using Date.parse()
, you can then use something like this:
var min = false, max = false;
// Find the minimum and maximum date
$('tr').each(function() {
// Acquire a numeric presentation somehow
var milliseconds = parseInt(Date.parse($(this).find('td.date').html()));
// Determine the min and max
min = milliseconds < min || !min ? milliseconds : min;
max = milliseconds > max || !max ? milliseconds : max;
});
$('tr').each(function() {
// Get the numeric presentation for current row
var milliseconds = parseInt(Date.parse($(this).find('td.date').html()));
// The relative position of the date, 0 = min date, 1 = max date
var position = (milliseconds - min) / (max - min);
// Generate color components
var red = Math.round(((0 - position) + 1) * 255).toString(16);
var green = Math.round(position * 255).toString(16);
// Build hex color string
red = red.length == 1 ? '0' + red : red;
green = green.length == 1 ? '0' + green : green;
var hex = '#'+red+green+'00';
// Apply the color
$(this).find('td').css('background-color', hex);
});
If it isn't clear from the code, this snippet will first find the minimum and maximum dates, then color the rows so that the minimum date is red and maximum green.
Hope this helps.
精彩评论