我得到了以下函数,它遍历所有 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 );
谢谢!