How to loop through table cells with jQuery and send the data to database
What's the best method for looping through a table, grabbing all the data in the cells, but skipping the开发者_StackOverflow中文版 <th>
? Do I put the data in an array?
Say you have a table that looks like this:
<table>
<tr>
<td>Information 1</td>
<td>Information 2</td>
</tr>
</table>
You could do something like this:
var cells = new Array();
$("table td").each(function(){
cells.push($(this).html());
});
What exactly are you looking to do with the data?
The easiest thing to do to skip the headers would to just remove them from the array after the loop is done.
After the code is done, you can run something like this:
cells = cells.slice(1, cells.length);
This will set the array to a copy of itself, minus the first element.
Alternatively, when you initially loop through it, only store the information if the index is greater than zero:
var cells = new Array();
$("table td").each(function(index){
if(index > 0){
cells.push($(this).html());
}
});
And finally, if you'd like to go with a more traditional javascript solution that does not require a condition:
var cells = new Array();
for(index = 1; index < $("table td").length; index++){
cells.push($("table td").get(index).html());
};
That way, you're starting from the second row.
精彩评论