Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cycle an odd/even class as it loops over the items?

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>
<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.

like image 577
John Mee Avatar asked Oct 25 '10 05:10

John Mee


2 Answers

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')
like image 60
John Mee Avatar answered Nov 03 '22 17:11

John Mee


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.

like image 25
bobef Avatar answered Nov 03 '22 16:11

bobef