gpt4 book ai didi

javascript - 连接表格单元格值并通过 javascript 重新格式化

转载 作者:行者123 更新时间:2023-12-01 03:42:12 29 4
gpt4 key购买 nike

样本:https://jsfiddle.net/5q9tddsh/

<table width="100%" >
<tbody>
<tr>
<td>id</td>
<td>book</td>
<td>colour</td>
<td>name</td>
<td>public</td>
</tr>
<tr>
<td>1</td>
<td>Book1</td>
<td>Red</td>
<td>This is a book one</td>
<td>#number1111111</td>
</tr>

<tr>
<td>2</td>
<td>Book2</td>
<td>White</td>
<td>This is a book two</td>
<td>#number2222222</td>
</tr>

<tr>
<td>3</td>
<td>Book3</td>
<td>Blue</td>
<td>This is a book three</td>
<td>#number33333333</td>
</tr>

<tr>
<td>4</td>
<td>Book4</td>
<td>Yellow</td>
<td>This is a book four</td>
<td>#number44444444</td>
</tr>
</tbody>
</table>


const table= document.getElementsByTagName("table")[0],
tableRow = table.querySelectorAll('tr');

tableRow.forEach((v, i) => {
v.querySelectorAll('td').forEach((v, i) => {
console.log(v);
});

});

如何连接每个 tr 值并用“:”分隔它们,并且每个 tr 都有一个新行。我坚持加入他们所以如下所示:

id:book:colour:name:public (start a new line '\n')
1:Book1:Red:This is a book one:#number1111111 (newline)

....

最佳答案

您可以映射元素并将它们连接起来

const table = document.getElementsByTagName("table")[0],
tableRow = Array.from(table.querySelectorAll('tr'));

let data = tableRow.map(v => {
return Array.from(v.getElementsByTagName('td')).map(x => x.innerText).join(":");
}).join("\n");

console.log(data);
<table width="100%">
<tbody>
<tr>
<td>id</td>
<td>book</td>
<td>colour</td>
<td>name</td>
<td>public</td>
</tr>
<tr>
<td>1</td>
<td>Book1</td>
<td>Red</td>
<td>This is a book one</td>
<td>#number1111111</td>
</tr>

<tr>
<td>2</td>
<td>Book2</td>
<td>White</td>
<td>This is a book two</td>
<td>#number2222222</td>
</tr>

<tr>
<td>3</td>
<td>Book3</td>
<td>Blue</td>
<td>This is a book three</td>
<td>#number33333333</td>
</tr>

<tr>
<td>4</td>
<td>Book4</td>
<td>Yellow</td>
<td>This is a book four</td>
<td>#number44444444</td>
</tr>
</tbody>
</table>

关于javascript - 连接表格单元格值并通过 javascript 重新格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43798364/

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