0

我得到了以下函数,它遍历所有 tableth并根据selectors值构建一个数组。

输出是一个数值数组,包含子对象作为值。

现在.get()允许我构建数组,但我不知道如何将其设置为关联数组。

问题:如何将第一个表格单元格值添加为关联数组索引?

( function( $ ) 
{
    $.fn.loadTableData = function( selectors )
    {
        var id = $( this ).attr( 'id' );

        /**
         * Get the output array keys from the <thead/tfoot> cell/th #ids
         */
        var columns = $( '#' + id + ' table th' ).map( function($) 
        {
            // This assumes that your headings are suitable to be used as
            // JavaScript object keys. If the headings contain characters 
            // that would be invalid, such as spaces or dashes, you should
            // use a regex here to strip those characters out.
            return jQuery( this ).attr( 'id' );
        } );

        /**
         * Get the cell data, based on the selector object values by index
         * @return row 
         */
        var cell_data = $( '#' + id + ' table tr' ).map( function( index )
        {
            var row = {};

            // Skip empty rows (example: <thead/tfoot>)
            if ( 0 === $( this ).find( 'td' ).length )
                return;

            // Find all of the table cells on this row.
            $( this ).find( 'td' ).each( function( index, value ) 
            {
                // Skip empty keys
                if ( undefined == selectors[ index ] )
                    return;

                // Determine the cell's column name by comparing its index
                // within the row with the columns list we built previously.
                var row_name = columns[ index ];

                // Add a new property to the row object, using this cell's
                // column name as the key and the cell's text as the value.
                if ( 'text' === selectors[ index ] )
                {
                    row[ row_name ] = $( this ).text();
                }
                else
                {
                    row[ row_name ] = $( this ).find( selectors[ index ] ).val();
                }
            } );

            // Finally, return the row's object representation, to be included
            //  in the array that $.map() ultimately returns.
            return row;

            // Don't forget .get() to convert the $ set to a regular array.
        } ).get();

        return cell_data;
    };
} )( jQuery );

谢谢!

4

2 回答 2

0

javascript 中没有关联数组。只需使用一个对象:

var myObject = new Object();

然后您可以在该对象中使用数字或字符串:

myObject = { 'foo' : 'bar' }

希望这可以帮助 :)

于 2012-05-19T15:55:52.977 回答
0

最后的解决方案并不难:使用.each()而不是,.map()然后分配给输出object[ final_index ]而不是使用.get().

于 2012-05-24T12:14:48.467 回答