Can I iterate through table with id="tbl" using JQuery with three columns and collect this value in three javascr开发者_开发百科ipt arrays ?
Here is an example
http://jsfiddle.net/SpE7F/
Javascript:
$().ready(function(){
var trArray = []
$('#tbl tr').each(function(){
var tdArray = []
$(this).find('td').each(function(){
tdArray.push($(this).text())
})
trArray.push(tdArray)
})
//console.log(trArray)
for(row = 0; row < trArray.length; row++){
for(cell = 0; cell < trArray[row].length; cell++){
alert('row: '+row+', cell: '+cell+' value: '+trArray[row][cell])
}
}
})
HTML
<table id="tbl" border="1">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
you can use this to find the Nth element in a 'tr'
so $("#tbl td").eq(2)
would get you the 3rd 'td'
Something like this should work.
firstCols = new Array();
secondCols = new Array();
thirdCols = new Array();
$(function() {
$("#tbl tr").each(function(i) {
var firstChild = $(this).children().first();
firstCols[i] = firstChild.text();
secondCols[i] = firstChild.next().text();
thirdCols[i] = firstChild.next().next().text();
});
});
You can loop through the columns and organize it via the index. This isn't a semantic table, but if you add the header/body just make sure to change the selector appropriately as well.
var arr = [];
$('#tbl td').each(function(){
var colId = $(this).index();
var rowId = $(this).parent().index();
if (arr[colId] == undefined) {
arr[colId] = [];
}
arr[colId][rowId] = $(this).html();
});
console.log(arr);
Here's the fiddle : http://jsfiddle.net/MfxA9/
Here's the HTML
<table id='tbl'>
<tr>
<td>Col 1 : Row 1</td>
<td>Col 2 : Row 1</td>
<td>Col 3 : Row 1</td>
</tr>
<tr>
<td>Col 1 : Row 2</td>
<td>Col 2 : Row 2</td>
<td>Col 3 : Row 2</td>
</tr>
<tr>
<td>Col 1 : Row 3</td>
<td>Col 2 : Row 3</td>
<td>Col 3 : Row 3</td>
</tr>
<tr>
<td>Col 1 : Row 4</td>
<td>Col 2 : Row 4</td>
<td>Col 3 : Row 4</td>
</tr>
</table>
Sure you can:
// Column-arrays
var col1 = new Array();
var col2 = new Array();
var col3 = new Array();
// Cache table
var table = $('#tbl');
// Iteratate over rows
var rows = table.find('tr');
rows.each(function() {
// Iterate over columns
var columns = this.children('td');
// Save column-values in separate arrays
col1.push(columns[0].html());
col2.push(columns[1].html());
col3.push(columns[2].html());
});
精彩评论