问题
I need to grab certain parts from many tables, save them and finally generate a new table using a jQuery template. But I am having problems collecting the first value.
HTML
<table>
<tr><td colspan="7"><a href="http://link/index.php?view=page&id=2961" target="_blank" title="title">atext1 atext2</a> - stuff 2 - <img src="img/icon_1.gif" class="icon" title="icon1" />12 - <img src="img/icon_2.gif" class="icon" title="icon2" />4 - <span title="long title"><img src="img/icon_3.gif" class="icon" /> stuff 5 </span></td></tr>
<tr><th><span title="title1">th1</span></th><th title="title2">th2</th><th title="title3">th3</th><th title="title4">th4</th><th title="title5">th5</th><th title="title6">th6</th><th title="title7">th7</th></tr>
<tr><td class="own" style="width:10px;"> </td><td><a href="http://link/index.php?view=page2&id=1413" target="_blank" title="title">text</a></td><td><img src="img/icon_4.png" class="icon link" title="icon4" onclick="dothis(118965,[1324,1835,2296,2443,2960,2961,2962,2964,2976,3186,4901,4974]);" /> <a href="javascript:dothat('div1',118965);" title="div1">text</a></td><td><a href="http://link/index.php?view=page3&newid=188898" target="_blank" title="page3">text</a></td><td class="right">24 (9)</td><td class="right">827</td><td class="right">11</td></tr>
MORE SIMILAR TRs HERE
</table>
JS
var savedData = [];
tbl = $('#table_1'); // Grab all content within div, which is a whole html table
var data = [];
$('tr', tbl).each(function(i, tr) {
// Begin the process to grab needed parts
if (i == 0) { // first row is special. it is colspan'ed
row = $('td', tr).html().split(' - '); // Splitting seems like the only way to get smaller html parts to work with
var a_href = $(row).find('a').attr('href'); // returns undefined
var a_href = $(row[0]).find('a').attr('href'); // returns undefined
var a_href = $('a', row).attr('href'); // returns undefined
var a_href = $('a', row[0]).attr('href'); // returns undefined
// Grab id only. I thought this would work
data['id'] = $('a', row[0]).attr('href').match(/view=page&id=([0-9]+)/)[1];
// Grab the other parts
} else {
// do stuff for other rows
}
});
savedData.push[data];
1) Why am I getting undefined ? 'row' becomes an array when splitting the inner html
2) I also have at least 1 tr with only th cells. Would it faster those rows where excluded from the .each(), like with a sub selector, or just ignore it (like if ($('td', tr).length > 0) { // do stuff }
) ?
3) If I just grab all text() from all td in all tr then using jQuery.map() is about 3-4 times faster than jQuery.each(i,v). Any idea why ?
I can use $('td[colspan], tr)
to grab first row, but jQuery.each() is easy to understand and thus to work with
4) When I need to use the collected parts in the template, can I then use savedData[0].id
?
回答1:
I got my answer here How to extract multiple parts from a html string with jQuery?
来源:https://stackoverflow.com/questions/4160003/problems-extracting-parts-from-rendered-html-tables-with-jquery