使用jQuery从表中获取值作为键值对 [英] get values from table as key value pairs with jquery
本文介绍了使用jQuery从表中获取值作为键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张桌子:
<table class="datatable" id="hosprates">
<caption> hospitalization rates test</caption> <thead>
<tr>
<th scope="col">Funding Source</th> <th scope="col">Alameda County</th> <th scope="col">California</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Medi-Cal</th>
<td>34.3</td>
<td>32.3</td>
</tr>
<tr>
<th scope="row">Private</th>
<td>32.2</td>
<td>34.2</td>
</tr>
<tr>
<th scope="row">Other</th>
<td>22.7</td>
<td>21.7</td>
</tr>
</tbody>
</table>
我想每行检索第1列和第2列的值,以成对的形式显示,如下所示[funding,number],[funding,number]
i want to retrieve column 1 and column 2 values per row as pairs that end up looking like this [funding,number],[funding,number]
到目前为止,我已经这样做了,但是当我发出警报时,它只显示[object,object] ...
i did this so far, but when i alert it, it only shows [object, object]...
var myfunding = $('#hosprates tbody tr').each(function(){
var funding = new Object();
funding.name = $('#hosprates tbody tr td:nth-child(1)').map(function() {
return $(this).text().match(/\S+/)[0];
}).get();
funding.value= $('#hosprates tbody tr td:nth-child(2)').map(function() {
return $(this).text().match(/\S+/)[0];
}).get();
});
alert (myfunding);
推荐答案
var result = $('#hosprates tbody').children().map(function () {
var children = $(this).children();
return {
name: children.eq(0).text(),
value: children.eq(1).text()
};
}).get();
这将构建以下形式的数组:
This will build an array in the form:
[
{ name : "...", value: "..." },
{ name : "...", value: "..." },
{ name : "...", value: "..." }
]
等
要获取第一行的名称,请使用:
To get the name of the first row, use:
alert(result[0].name);
对于值:
alert(result[0].value);
,如果您想要的结果与指定的完全相同:
if you want the result EXACTLY as you specify:
var result = $('#hosprates tbody').children().map(function () {
var children = $(this).children();
return "[" + children.eq(0).text() + "," + children.eq(1).text() + "]"
}).get().join(",");
这篇关于使用jQuery从表中获取值作为键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文