简体   繁体   中英

Maintain Table Alternate Row Background after dynamically adding then hiding a new row

http://jsfiddle.net/bfa78/1/

I have table in which i have alternate rows with different background colour using CSS:

table tr:nth-child(2n){
    background:#f8f8f8;
}

My Application requires me to dynamically add and hide new rows to the table ( as shown in the Fiddle) .

$('#addrow').on('click',function(){

    $('#datagrid').find('tr:nth-child(2)').after(' <tr class="newrow">  <td>sa</td><td>asd</td><td>sdsa</td><td>sda</td>   </tr>');

});

$('#hiderow').on('click',function(){

    $('#datagrid').find('tr.newrow').fadeOut(400);


});

The problem is when i am adding a new row and then hiding that row , the alternate background pattern breaks . Is there a way I can fix it? I tried giving different classnames to the original rows and applying the above css on them but its not helping.

You're setting the alternate style only to the rows that have the original class. But you're adding rows with a different class name ( newrow ).

Change from:

table tr.original:nth-child(2n){

to general rows selection:

table tr:nth-child(2n){

http://jsfiddle.net/bfa78/3/

you need to apply colors with javascript

   function applycolors(){
var trs= $('#datagrid tr:not([style="display: none;"])') ;
    for(var i=0;i<trs.length;i++){
        if(i%2!=0){
         trs[i].style.background="#f8f8f8";
        }else{
         trs[i].style.background="#ffffff";
        }
    }
}

http://jsfiddle.net/vikramjakkampudi/bfa78/6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM