开发者

Set color of alternate row using jQuery?

I am trying to use query to set color of alternate rows of a html table. But every time I add a new row query switches the color of the whole table. Here is the Javascript code I am using:

var alternate = true;
function addRow(data) {
    if(alternate){
        $("table.live_feed").find('tbody.main').prepend(data).css("background", "#f1f1f1");开发者_开发百科
        alternate = false;
    }else{
        $("table.live_feed").find('tbody.main').prepend(data).css("background", "white");
        alternate = true;
    }
}

PS: I looked as some similar questions on Stack Overflow where they change the color of odd or even rows. I do not want to change the color of rows that are already present, I only want to change the color of new rows being added.


Your .css is acting on the found item (tbody.main), instead you want it to act on data:

var data = $(data).css("background", "#f1f1f1");
$("table.live_feed").find('tbody.main').prepend(data);

As a side note, for alternating row colours you can utilise the selectors :odd and :even

Example:

$('tr:odd').css('background', 'lightgray');


prepend and append and other DOM insertion methods don't return the just created elements, but the jQuery object where you called them. In your code, the css call is applied to the tbody.main jQuery object.

In this example you can see how the returned element of the append call is the div element with test id.

http://jsfiddle.net/marcosfromero/VUrhZ/

In the same example you can see a workaround to apply css to the just inserted element using first() after prepend.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜