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

时间:2017-05-05 06:53:25

标签: javascript

示例: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值,并用&#34; :&#34;分隔它们,每个tr都有一个新行。我坚持加入他们 如下所示:

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

....

1 个答案:

答案 0 :(得分:2)

您可以映射元素并加入它们

using (var myContext = new MyDBContext())
{
    var myData = myContext.MyData.Where(x => x.id == id);
    if (myData.Count() > 0)
    {
        //blah;
        return true;
    }
    else
    {
        return false;
    }
}
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);