HTML转换表在JavaScript数组 [英] Convert html table to array in javascript
本文介绍了HTML转换表在JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想问一下是有可能的HTML表格转换成数组在JavaScript?谢谢。我有这个表。我还没有尝试任何事情。
更新
<表ID =cartGrid>
<&THEAD GT;
&所述; TR>
<第i个项目说明与LT; /第i
<第i个数量< /第i
<第i个单价和LT; /第i
<第i个分机价格和LT; /第i
< / TR>
< / THEAD>
<&TBODY GT;
< TR>< TD>旧灯泡< / TD>< TD> 1< / TD>< TD> 107.00< / TD>< TD> 107.00< / TD>
< TR>< TD>蓝帖< / TD>< TD> 2< / TD>< TD> 7.00< / TD>< TD> 14.00< / TD>
< / TBODY>
< /表>
解决方案
下面是做你想要什么的一个例子。
VAR myTableArray = [];$(#表TR cartGrid)。每个(函数(){
变种arrayOfThisRow = [];
VAR资料表= $(本).find('TD');
如果(tableData.length大于0){
tableData.each(函数(){arrayOfThisRow.push($(本)的.text());});
myTableArray.push(arrayOfThisRow);
}
});警报(myTableArray);
您也许可以在此展开,也就是说,使用TH的文本,而不是为每个TD一键 - 值对。
由于这实现使用一个多维数组,你可以做这样的事情访问行和TD:
myTableArray [1] [3] //第四届第二tablerow的TD的
编辑:这里是你的例子小提琴: http://jsfiddle.net/PKB9j/1/
I would like to ask is it possible to convert an HTML TABLE into Array in javascript? Thank you. I have this table. i haven't tried anything yet.
update
<table id="cartGrid">
<thead>
<tr>
<th>Item Description</th>
<th>Qty</th>
<th>Unit Price</th>
<th>Ext Price</th>
</tr>
</thead>
<tbody>
<tr><td>Old Lamp</td><td>1</td><td>107.00</td><td>107.00</td>
<tr><td>Blue POst</td><td>2</td><td>7.00</td><td>14.00</td>
</tbody>
</table>
解决方案
Here's one example of doing what you want.
var myTableArray = [];
$("table#cartGrid tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
You could probably expand on this, say, using the text of the TH to instead create a key-value pair for each TD.
Since this implementation uses a multidimensional array, you can access a row and a td by doing something like this:
myTableArray[1][3] // Fourth td of the second tablerow
Edit: Here's a fiddle for your example: http://jsfiddle.net/PKB9j/1/
这篇关于HTML转换表在JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文