jQuery: linearizzare le tabelle di dati su mobile

Con jQuery possiamo linearizzare le tabelle di dati sui dispositivi mobili.

Possiamo creare il seguente plugin che trasforma una tabella in una serie di liste di definizione:


(function( $ ) {
	$.fn.linearize = function( options ) {
        options = $.extend(
            {
                wrapClass: "table",
                emptyClass: "empty"
            },

            options
        );
    	return this.each(function() {
            var $element = $( this );
            var $th = $element.find( "th" );
            var $tr = $element.find( "tbody tr" );
            var html = '<div class="' + options.wrapClass + '">';
            
            $tr.each(function() {
                html += '<dl>';

                $( this ).find( "td" ).each(function( i ) {
                    var $header = $th.eq( i );
                    if( $header.length ) {
                        html += '<dt>' + $header.text() + '</dt><dd>' + $( this ).html() + '</dd>';
                    } else {
                        html += '<dt class="' + options.emptyClass + '"></dt><dd>' + $( this ).html() + '</dd>';
                    }
                });

                html += '</dl>';
            });

            html += '</div>';

            $element.replaceWith( html );
        });
	};
})( jQuery );

Esempio d'uso:


$(function() {
    if( /mobile/i.test( navigator.userAgent ) ) {
        $( "table" ).linearize();
    }
});

Torna su