2017-05-05 3 views
0

Beispiel: https://jsfiddle.net/5q9tddsh/Join-Tabelle Zellenwerte und Neuformatierung von Javascript

<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); 
    }); 

}); 

Wie kann ich jeden tr Werte verbinden und getrennt sie von einem „:“, und jeder tr hat eine neue Zeile. Ich stecke auf sie verbindenden so aussehen wie unten:

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

.... 

Antwort

2

Sie können die Elemente der Karte über und verbinden sie

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>

Verwandte Themen