开发者

How do I remove a tr then apply background-color to odd tr's?

开发者 https://www.devze.com 2022-12-18 11:29 出处:网络
on doc.ready, I\'ve done $(\"tr:even\").css(\"background-color\",\"orange\");.I then have a button that does the following: $(\"#tr3).remove() which removes the 3rd tr (I id\'ed the third tr \"tr3\").

on doc.ready, I've done $("tr:even").css("background-color","orange");. I then have a button that does the following: $("#tr3).remove() which removes the 3rd tr (I id'ed the third tr "tr3"). I then apply the orange bgcolor to even rows AGAIN in order to update the tr bgcolors now that the table has 1 less tr, but the tr 开发者_如何学Cbgcolor's don't refresh. I end up with 2 orange tr's in a row, instead of having every other tr be orange background. make sense?


It would be easier if you made that background color a css class:

.odd { background-color: orange; }

Then in javascript:

$(function() {
  $("tr:even").addClass("odd");
  $("#button").click(function() {
    $("#tr3").remove();
    $("tr").removeClass("odd").filter(":nth-child(odd)").addClass("odd");
  });
});


try applying also on the odd one:

$("tr:odd").css("background-color","your color");
$("tr:even").css("background-color","orange");

as I think it is because when you remove the 3rd tr, all tr next to it changes. the odd becomes even and the even becomes odd.


You can use this to access the nth element:

$("tr:nth-child(3n)") //will match with 3rd, 6th, ...

you can change 3n or do simple add and substract to it:

$("tr:nth-child(3n+1)") //will match with 1st, 4th, 7th, ...
$("tr:nth-child(3n+2)") //will match with 2nd, 5th, 8th, ...

:nth can be used in filter too, for example:

$(SELECTOR).filter(":nth-child(3n)")

I hope this is what you looking for.

UPDATE:

After re-read your question, I thing I got it wrong.

In my code, I put the code in separated function:

function zebra_table($) {
  $("tr").removeClass("odd");
  $("tr:odd").addClass("odd");
}

Then after I change the table's row, such as delete one of it, or add new row, I will simply call the function above:

jQuery(function($){
  //after DOM loaded, apply zebra
  zebra_table($);

  //...
  //after modify table
  zebra_table($);
});

The key is, make the table 'plain' again, then re-apply the zebra rules in the current table structure.


All, thanks so much for your help!!! I ended up doing the following:

$(document).ready(function() {
    $("tr:odd").addClass("odd");
    $("#button").click(function () {
        $("#tr3").remove();
        $("tr").removeClass("odd");
        $("tr:odd").addClass("odd"); // re-add class to odd tr's
    });
});

and that worked! Didn't need to do any filter(n) stuff. Thanks again for the help!!!

0

精彩评论

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

关注公众号