Javascript - Extract text from a page then build an array with it
I have a table of data that I want to grab text from, stick into an array (and then use with Google maps).
The table looks like:
<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>
I want to grab the text from the table cells and build an array of it all. Something like:
var foo = [
['Bob', 12345],
['Jane', -55.34]
]
What I tried, using jquery, was:
var foo = [];
$('.bar').each(function(){
foo.push($('.name').text(), $('.number').text());
});
But that, obviously, does not work giving (and I'm pretty sure I'm just using the select开发者_JAVA技巧or the wrong way):
["BobJane", 12345-55.34]
So how do you get the contents from each TD within each TR and build the array with it so I get the desired above example (with each set of data in it's own row)?
You could do it using .map()
to construct a jQuery object of the values, and .get()
to pull the Array out of it.
Try this:
var array = $('.bar').map(function() {
var $ch = $(this).children('td');
return [ [ $.text( [$ch[0]] ), $.text( [$ch[1]] ) ] ];
}).get();
Note that when returning an Array inside .map()
, you need to wrap it in another Array.
You're almost there:
var foo = [];
$('.bar').each(function(){
var self = $(this);
foo.push([self.children('.name').text(), self.children('.number').text()]);
});
You were previously pushing two new values onto the foo
array. The above code pushes one value (which is an array containing two elements). You also needed to search within the current table row for the correct name
and number
, which you can do using children
.
If it helps you to understand, the above code can be broken down into:
var foo = [];
$('.bar').each(function(){
var self = $(this);
var row = [self.children('.name').text(), self.children('.number').text()];
foo.push(row);
});
Pass this
as a context to the selectors inside each
so as to only get one name/number at a time. Also make sure to pass an array []
to push
function, instead of two entries.
var foo = [];
$('.bar').each(function () {
var name = $('.name' , this).text(); // name from the current .bar
var number = $('.number', this).text(); // number from the current .bar
foo.push( [ name, number ] ); // notice []
});
精彩评论