Vcv
Vcv

Reputation: 3

Have jquery filter inside live event

Hi I have this following code with jquery , so it will alternate colors on each row of a table:

  $("tr").filter(':nth-child(2n+1)').addClass('odd').next().addClass('even');  

but unfortunately it doesnt work when the table comes from an ajax call .. is there a way to put this into a $("tr").live... and make it work like that? .. I have tried different aproaches like this: ( I know the syntax may not be correct ).

$("tr").live({ 
 $("this").filter(':nth-child(2n+1)').addClass('odd').next().addClass('even')
});  

But doestn seem to work

Upvotes: 0

Views: 341

Answers (2)

AbstractChaos
AbstractChaos

Reputation: 4211

Its possible to use the :odd and :even tags for example

JSfiddle example

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237865

live isn't a catch-all solution for problems that come from dynamic content. It only works with events. Normally, you listen for events with bind; when your content is dynamic, live is a way to capture events reliably. So you need another solution for styles...

The simplest solution is to define your CSS using nth-child:

tr:nth-child(2n+1) {
    // whatever the odd styles are
}

tr:nth-child(2n) {
    // whatever the even styles are
}

This won't work in all browsers, since it's CSS3. (In particular, it won't work in Firefox 3 or Internet Explorer before version 9.)

The other solution is to update all the tr elements on the page after every AJAX call using ajaxComplete:

$(document).ajaxComplete(function() {
    $('tr:nth-child(2n+1)').addClass('odd').next().addClass('even');
});

This won't have great performance, but it probably won't be a particular drain as it will always happen asynchronously. This will, obviously, work cross-browser.

Upvotes: 1

Related Questions