猿问

使用javascript将HTML表格数据转换为数组形式

我有一个问题,即使我将表数据存储到数组中,数组也显示未定义 

以数组的形式获取每个问题的行

function getAllProblemRowElements() {

    //var k = document.querySelector("#app > div > div > div > div.table-responsive > table > tbody");

    const tableContents = document.querySelector("#app > div > div > div > div.table-responsive > table > tbody");

    const sources = Array.from(tableContents,source=>tableContents[0]);

    return sources;


请解决


RISEBY
浏览 178回答 3
3回答

慕丝7291255

表内容转数组var myTableData = Array.prototype.map.call(document.querySelectorAll('#myTable tr'), function(row){&nbsp; return Array.prototype.map.call(row.querySelectorAll('td'), function(td){&nbsp; &nbsp; return td.innerHTML;&nbsp; &nbsp; });&nbsp; });console.log(myTableData)<table id="myTable"><tr>&nbsp; <td>1</td>&nbsp; <td>a</td></tr><tr>&nbsp; <td>2</td>&nbsp; <td>b</td></tr><tr>&nbsp; <td>3</td>&nbsp; <td>c</td></tr></table>

茅侃侃

这是ES6版本const myTableData = [...document.querySelectorAll('#myTable tr')]&nbsp; .map(row => [...row.querySelectorAll('td')]&nbsp; &nbsp; .map(cell => cell.textContent));console.log(myTableData)<table>&nbsp; <tbody id="myTable">&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>1</td>&nbsp; &nbsp; &nbsp; <td>a</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>2</td>&nbsp; &nbsp; &nbsp; <td>b</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>3</td>&nbsp; &nbsp; &nbsp; <td>c</td>&nbsp; &nbsp; </tr>&nbsp; </tbody></table>

潇潇雨雨

我假设您的问题中定义的问题行是标题。您可以使用querySelectorAllindocument获取所有行,然后将其映射到数组中。希望下面的代码有帮助:function getAllProblemRowElements() {&nbsp; &nbsp; const tableContents = document.querySelectorAll("#app > div > div > div > div.table-responsive > table > tbody > tr");&nbsp; &nbsp; const sources = Array.from(tableContents,source=>source.children[2].getAttribute("value"))&nbsp; &nbsp; return sources;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答