gpt4 book ai didi

javascript - 在数组数组中查找表数据存储

转载 作者:行者123 更新时间:2023-11-28 08:40:26 24 4
gpt4 key购买 nike

我需要从表中获取数据并将其存储在数组中。表的每一行都应该是数组中的一个新数组。基本上 html 看起来像这样:

<table id="contactlisttable">
<tr>
<th>Name</th>
<th>Title</th>
<th>Phone</th>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Joey</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Anthony</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
</table>

等等...

这是我的代码

jQuery(document).ready(function(){
$(function(){
var $table = $("#contactlisttable"),
$headerCells = $table.find("tr th"),
$myrows = $table.find("tr"); // Changed this to loop through rows

var headers = [],
rows = [];

$headerCells.each(function() {
headers[headers.length] = $(this).text();
});

$myrows.each(function() {
$mycells = $myrows.find( "td.contactlist" ); // loop through cells of each row
cells = []
$mycells.each(function() {
cells.push($(this).text());
});
if ( cells.length > 0 ) {
rows.push(cells);
}
});
console.log(headers);
console.log(rows);
});
});

我当前的代码输出

[["Waddell, Joey", "webdesigner", "", 15 more...], ["Waddell, Joey", "webdesigner", "", 15 more...],

期望的输出是:

["Name","Title","Phone"]
[["Joey","webdesigner","555555"]
["Anthony","webdesigner","555555"]]

最佳答案

我认为这可以更简单:

Live Demo

JS

$(function(){
var results = [];
var row = -1;
$('#contactlisttable').find('th, td').each(function(i, val){
if(i % 3 === 0){ //New Row?
results.push([]);
row++;//Increment the row counter
}
results[row].push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)
});
console.log(results);
});
<小时/>

编辑

这里有一个更好的解决方案(兼容 IE9+)。与我之前的解决方案不同,它考虑了可变的行长度。

Live Demo

JS

//IE9+ compatable solution
$(function(){
var results = [], row;
$('#contactlisttable').find('th, td').each(function(){
if(!this.previousElementSibling){ //New Row?
row = [];
results.push(row);
}
row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)
});
console.log(results);
});

关于javascript - 在数组数组中查找表数据存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20552883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com