javascript - Alternating row color based on previous row using jquery -
i have table of dynamically generated content (php mysql). first column date. records share same date.
my goal style records same date same background color , date appear in first event of day.
i'm no javascript/jquery expert, here first go. not yet functional. here 2 problems:
1: cannot repeated dates disappear (see note in code)
2: whole method of adding classes according content of cell above seems incredibly slow. page loads around 10-12 seconds table of 100-150 rows. fastest method achieve this?
$(document).ready(function(){ $("td.date").each(function(){ var cellabove = $(this).parent().prev().children(".date").html(); if ($(this).html()!==cellabove){$(this).parent().addclass("firstdate");} if ($(this).html()==cellabove){$(this).parent().addclass("multidate");} }); $("tr.firstdate").filter(":even").css("background-color","#ffffff"); $("tr.firstdate").filter(":odd").css("background-color","#f4f4f4"); $("tr.multidate").each(function(){ $(this).children(".date").text(); //not functioning $(this).css("background-color",$(this).prev().css("background-color")); }); }); <table> <tr> <td>date</td> <td>event</td> </tr> <tr> <td class="date">january 5, 2013</td> <td>board meeting</td> </tr> ... </table>
i think fastest implementation filter out values , set html classes server-side using php.
but went ahead , wrote js version anyways (and morning problem-solving) =)
your first function @ 2n
algorithm because running 2 different loops. first suggestion work in first loop. also, every time use jquery selector, performing loop. jquery isn't instantaneous, , traversing dom elements (another loop!) find elements. count 7 jquery selectors in code, , 2 "each" loops, total of 9 loops. can save jquery objects if reused, don't have "re-loop" acquire them. example, in future can save $("tr.firstdate")
object in variable since use twice. in code, can see save $me
variable future use. if wanted make faster, save $me.html()
value well. using approach larger applications, have consider trade-off of memory size vs. speed.
also, used .html("")
method clear contents of cells wanted empty.
another suggestion use css decide color, rather setting color using jquery. add class , have css work. can see in code add .alt
class rows want alternate color.
.alt td { background: #666; }
also, don't rely on styling tr
background color. don't think supported cross-browser. style td
instead. also, in jsfiddle used th
tags headers, semantic purposes.
here jsfiddle. javascript below:
$(document).ready(function(){ var parity = true; var curdate = null; $("td.date").each(function(){ var $me = $(this); if(curdate == null || curdate != $me.html()) { curdate = $me.html(); parity = !parity; } else $me.html(""); if(parity) $me.parent().addclass("alt"); }); });
hope helps!
Comments
Post a Comment