Coding alternative shaded rows?
开发者_C百科I want alternative rows in my table to be shaded. what is the best way to do this, javascript, rails?
Today, i do a simple <% num % 2%>, but this is such a common operation that i think there should be a smarter way to do it
If you're willing to do it on the server side, rails intended way is for you to use the "cycle" method, this will handle the modulus 2 stuff, but will also handle namespacing if you need to do nested alternating shading.
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001753
e.g.
<%= cycle("even", "odd", :name => "row_class") -%>
The name is just used to avoid collisions if you've got 2 cycles going on at the same time, it's optional.
You can do that very easily using jQuery, if that's an option. Link to the jQuery library in the head, and ideally give the table an id or class so that you can identify it, and create a class that half the rows will get. Then, put this in your javascript:
jQuery(document).ready(function() {
jQuery('#table tr:even').addClass('stripes'); //could also be tr:odd
});
That's it, really. If you don't want to create a separate class, you can always add the style on the fly:
jQuery(document).ready(function() {
jQuery('#table tr:even').css({'backgroundColor: blue', 'font: red'});
});
This is actually built-in to Rails - check the "cycle" method in ActionView Helpers.
精彩评论