我有一个数据表,我想从中抓取文本,粘贴到一个数组中(然后与 Google map 一起使用)。
表格如下所示:
<table>
<thead>
<tr>
<th>One</th>
<th>Two</th>
</tr>
</thead>
<tr class='bar'>
<td class='name'>Bob</td>
<td class='number'>12345</td>
</tr>
<tr class='bar'>
<td class='name'>Jane</td>
<td class='number'>-55.34</td>
</tr>
</table>
我想从表格单元格中获取文本并构建一个包含所有文本的数组。像这样的东西:
var foo = [
['Bob', 12345],
['Jane', -55.34]
]
我使用 jquery 尝试过的是:
var foo = [];
$('.bar').each(function(){
foo.push($('.name').text(), $('.number').text());
});
但是,显然,这不起作用(而且我很确定我只是以错误的方式使用选择器):
["BobJane", 12345-55.34]
那么如何从每个 TR 中的每个 TD 获取内容并用它构建数组,以便我得到上面所需的示例(每组数据都在其自己的行中)?
最佳答案
你可以做到using .map()
构造值的 jQuery 对象 and .get()
将数组从中取出。
试试这个:
var array = $('.bar').map(function() {
var $ch = $(this).children('td');
return [ [ $.text( [$ch[0]] ), $.text( [$ch[1]] ) ] ];
}).get();
请注意,当在 .map()
中返回数组时,需要将其包装在另一个数组中。
关于Javascript - 从页面中提取文本,然后用它构建一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3842416/