如何提取td的文本内容并将每个文本内容存储到包含以下内容的另一个数组的数组中:
//create two element in the array, that store a string containing html code
tablecontentArray[0] = "`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr><td>Fruit 1</td><td>Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr><td>Fruit 3</td><td>Fruit 4</td></tr></tbody>`"
tablecontentArray[1] = "`<tbody><tr><th>Title 5</th><th>Title 6</th></tr><tr><td>Fruit 5</td><td>Fruit 6</td></tr><tr><th>Title 7</th><th>Title 8</th></tr><tr><td>Fruit 7</td><td>Fruit 8</td></tr></tbody>`"
//loop to extract the td text content from the each element of the tableContentArray and store it into extractedTdArray
extractedTdArray = [];
答案 0 :(得分:0)
设置一个表并按
var extractedTdArray = [];// create result array
// loop across html strings
$.each(tablecontentArray, function (key, table) {
$('#table').html(table);//create html table
// loop across the created table td's
$.each($('#table').find('td'), function (key2, td) {
var tdVal=$(this).text();// td value
//push to array
extractedTdArray.push(tdVal);
});
});
});
设置多个表格和地图
// set tables
$.each(tablecontentArray, function (key, table) {
$('#table' + key).html(table).addClass('table');
});
// map td
var extractedTdArray = $('.table tr:has(td)').map(function (i, v) {
return $(this).text();
}).get();
答案 1 :(得分:0)
var str = "`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr><td>Fruit 1</td><td>Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr><td>Fruit 3</td><td>Fruit 4</td></tr></tbody>`"
var extractedTdArray = str.split("<td>")
.filter(function(v){ return v.indexOf('</td>') > -1})
.map( function(value) {
return value.split("</td>")[0]
})
console.log(extractedTdArray)
首先,您可以通过<td>
将字符串拆分为数组
0:"`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr>"
1:"Fruit 1</td>"
2:"Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr>"
3:"Fruit 3</td>"
4:"Fruit 4</td></tr></tbody>`"
然后,您将使用</td>
filter
的元素
0:"Fruit 1</td>"
1:"Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr>"
2:"Fruit 3</td>"
3:"Fruit 4</td></tr></tbody>`"
然后你用</td>
拆分它并得到第一个元素。我们已经按<td>
进行了拆分,因此我们知道从一开始就是我们想要</td>
的信息。
["Fruit 1", "Fruit 2", "Fruit 3", "Fruit 4"]