Using the jquery-tmpl, I want to stripe presentation of the rows by adding a class to every second one, so from data ['Cat','Dog','Horse','Noddy'] it generates:
<li>Cat</li>
&l开发者_如何学Ct;li class="odd">Dog</li>
<li>Horse</li>
<li class="odd">Noddy</li>
The solutions suggested here looked like the start of something that could be further refined for easy digestion by us noddy's.
Never mind. Overcomplicating things as usual...
Just follow it up with the :odd selector with addClass...
$('#template').tmpl(data).appendTo('#list')
$("#list li:odd").addClass('odd')
Just found the solution after few trial and errors. You can use the {{= }} tag for evaluating expression:
{{each(i) Animals}}<li class="{{= i % 2 ? 'even' : 'odd'}}">...</li>{{/each}}
Of course you can modify it to suit your needs exactly - you can put the class inside and print empty value for odd or even.
Another solution would be to use a function (there is example of this in the jquery tmpl docs), but it is ugly.
@John Mee, I don't think you are overcomplicating.
Imho the template is the place where the addition of the odd-Class should take place. Logic and performance wise.
Here is a patch for having the index inside a nested template. If you like to have an additional $odd property it could be easily extended as follows:
jQuery.map( data, function( dataItem, index ) {
if(dataItem){
dataItem.$index = index;
dataItem.$odd = index % 2 === 1;
}
精彩评论