문제

I'm using

$(".entry").filter(":odd").addClass('alt');

within $(document).ready() to facilitate zebra striping of everything with class 'entry'.

In the course of interacting with the page, new DOM elements with class 'entry' are appended one-by-one at the end. I'd like to use something similar to the above to make sure the newly appended entry has the appropriate background color, meaning the opposite color of whatever 'entry' preceded it.

I can't think of an elegant (or really any) way to do this. Any ideas? Is there something analogous to .live() that would apply this rule to all current and future matches?

UPDATE

edit: moved update to answer

도움이 되었습니까?

해결책 4

This solution isn't nearly as elegant as the CSS answers, but it does exactly what I need it to without any of the distracting side effects:

First I chain this on the tail end of the DOM append:

$('#articles').append('putyourDOMelementinhere').addClass('new');

Then I have a clumsy conditional statement to check whether the previous entry has the 'alt' class, and if it doesn't, I use .addClass('alt'). Then I clean up by plucking off the 'new' class:

 if(!$('.new').prev().hasClass('alt')){
  $('.new').addClass('alt');
 }
 $('.new').removeClass('new');

I'm sure the jQuery gurus out there could come up with a much sexier solution, but this seems to do just what I had in mind.

다른 팁

Live Demo

You could try the following with just simple CSS.

.entry:nth-child(odd){
    /* do some styling */
}

One way would be to run

$(".entry").filter(":odd:not(.alt)").addClass('alt');

whenever you append at new elements..

A more correct is to handle this through CSS

.entry:nth-child(odd){
//styling of the .alt goes here
}

and this will work for new elements as well..

you can just call the filter function whenever you update the table.

$(document).ready(function() {
    $('tr').filter(':odd').addClass('alt');

    $('#adder').click(function() {
        $('tbody').append('<tr><td>Item 1</td><td>Item 2</td></tr>');
        $('tr').filter(':odd').addClass('alt');
    });
});

example JSFiddle: http://jsfiddle.net/Gvdcv/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top