gpt4 book ai didi

javascript - 使用 foreach 循环遍历表创建数组

转载 作者:行者123 更新时间:2023-11-29 22:02:07 25 4
gpt4 key购买 nike

我有一个像这样的表格:

<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 变量中。

提前致谢

最佳答案

应该这样做 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));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>

<hr/>

<pre id="result"></pre>

关于javascript - 使用 foreach 循环遍历表创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23183595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com