2014-04-20 22 views
1

创建foreach循环阵列我有一个形式与表是这样的:JavaScript的 - 通过表

<table id="preview"> 
<tbody> 
<tr> 
<td>01/01/2010</td> 
<td>Credit</td> 
<td>1000</td> 
</tr> 
<tr> 
<td>01/05/2010</td> 
<td>Debit</td> 
<td>200</td> 
</tr> 
<tr> 
<td>01/09/2010</td> 
<td>Debit</td> 
<td>400</td> 
</tr> 
<tr> 
<td>01/11/2010</td> 
<td>Debit</td> 
<td>100</td> 
</tr> 
</tbody> 
</table> 

现在我需要建立一个数组来发送(AJAX/PHP)是这样的:

$ajaxArray = array( 0 => array(From => "01/01/2010", //1st td of the 1st Row 
            To  => "01/05/2010", //1st td of the 2nd Row 
            Type => "Credit", 
            Amount => 1000.00), 
         1 => array(From => "01/05/2010", //1st td of the 2nd Row 
            To  => "01/09/2010", //1st td of the 3th Row 
            Type => "Debit", 
            Amount => 200.00), 
         2 => array(From => "01/09/2010", //1st td of the 3th Row 
            To  => "01/11/2010", //1st td of the 4th Row 
            Type => "Debit", 
            Amount => 400.00), 
         3 => array(From => "01/11/2010", //1st td of the 4th Row 
            To  => "01/01/2012", //Value in $last_date var 
            Type => "Debit", 
            Amount => 100.00) 
     ); 

我试着用这个代码:

$('#preview > tbody > tr').each(function() { 
      var from = $('td:eq(0) ', this).text(); 
      var type = $('td:eq(1) ', this).text(); 
      var amount = $('td:eq(2) ', this).text(); 
      ajaxArray.push({ 
       From: from, 
       Type: type, 
       Amount: amount 
      }); 
     }); 

正如你可以看到我不能让“到”日期值。 “To”日期值是除最后一行以外的下一行的第一个TD中包含的日期,其中此值位于$ last_date变量中。

在此先感谢

回答

1

这应该这样做Fiddle Demo

var array = []; 
var rows = $("#preview tbody tr"); 

$.each(rows, function(index, row) { 
    var columns = $(row).find("td"); 

    array[index] = {};    
    array[index].from = columns[0].innerHTML;  
    array[index].type = columns[1].innerHTML; 
    array[index].amount = columns[2].innerHTML; 

    if(index > 0){ 
     array[index - 1].to = columns[0].innerHTML; 
    }  
}); 

$("#result").text(JSON.stringify(array)); 
+0

非常感谢。除了最后一个数组外,这段代码对每一行都是完美的。如何从$ last_date变量获取最后一个日期? – fasenderos

+0

我不知道,没有经验的PHP对不起。 – Hatsjoem

+0

好的没问题。我可以通过添加最后一个“To”日期的隐藏行来解决问题。 – fasenderos