Easiest way to alternate row colors in PHP/HTML?

前端 未结 19 1948
無奈伤痛
無奈伤痛 2020-12-01 03:41

Here\'s a PHP example of mine. Can anyone find a shorter/easier way to do this?


    
19条回答
  •  孤城傲影
    2020-12-01 04:37

    You can abuse the $GLOBAL scope to store the current selected class state, see below table_row_toggle() function. Yes, I know its dirty to abuse the $GLOBAL scope, but hey, we're here to fix problems ain't we? :)

    Calling the table row toggle function in HTML:

    >
    

    The function in PHP:

    /* function to toggle row colors in tables */
    function table_row_toggle() {
        /* check if $trclass is defined in caller */
        if(array_key_exists('trclass', $GLOBALS)) {
            $trclass = $GLOBALS['trclass'];
        }   
    
        /* toggle between row1 and row2 */
        if(!isset($trclass) || $trclass == 'row2') {
            $trclass = 'row1';
        } else {
            $trclass = 'row2';
        }   
    
        /* set $trclass in caller */
        $GLOBALS['trclass'] = $trclass;
    
        /* write the desired class to the caller */
        echo ' class="' . $trclass . '"';
    }
    

提交回复
热议问题