English 中文(简体)
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.

最佳回答

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;
    }




相关问题
Making jquery tmpl without a lot of extra script tags

I ve been reading about the jQuery template plugin http://api.jquery.com/tmpl/ as a means of binding data to markup. All the examples seem to show that you define the template in a script new script ...

How do I render a jQuery.tmpl Template to a String?

The documentation for jquery.tmpl uses .appendTo to insert the template into the DOM during the rendering process: $.tmpl( myTemplate, myData ).appendTo( "#target" ); I am attempting to convert an ...

how to tell if a property exists and is false

I am having a hard time determining if data passed into the jquery template exists and is false without getting errors. This is what I am using to test <html> <head> <title>jQuery ...

热门标签