2016-06-28 1 views
0

특정 조건을 통과하면 대상 속성을 배열로 푸시하는 for 루프가 있습니다. 각 항목을 자체 행에 출력하는 테이블을 만들고 싶습니다. 자신을위한 까다로운 부분은 이것이 어떻게 동적으로 수행 될 수 있는지 이해하는 것입니다. 배열의 각 항목을 쉽게 하드 코딩하여 행에 삽입 할 수 있습니다. 하지만이 작업은 pure JS를 사용하여 자동으로 수행 할 수 있습니까?배열의 각 항목을 반복하여 HTML로 출력 할 수 있습니까?

var header = 
      "<thead>" + 
      "<tr>" + 
      "<td class='legend-color-guide'><div style='background-color: " + series.color + ";'></div></td>" + 
      "<td class='key'>" + " My Table:</td>" + 
      "</tr>" + 
      "</thead>"; 

var rows = 
      "<tr>" + 
      "<td class='key'><strong>" + <INSERT HERE> + "</strong></td>" + 
      "</tr>" 

return "<table>" + header + "<tbody>" + rows +"</tbody>" + "</table>"; 
:

script.js

같은 파일에서
var myArray = []; 
for (var i = 0; i < ccirdata.length; i++) { 
    if (ccirdata[i].catType === 'I') {  
     myArray.push(ccirdata[i].catNum); 
    } 
}; 

난 '에서 myArray'에서 반복을 삽입하기 위해 노력하고있어 내 테이블에 대한 개요를

myArray의 각 항목에 대해 동적으로 새 행을 만들 수 있습니까?

+0

시도한 내용은 무엇입니까? –

+3

* "배열의 각 항목을 반복하여 HTML로 출력 할 수 있습니까?"- 물론. 질문의 코드는 for 루프를 사용하여 목록을 반복하는 방법을 이미 알고 있으며 문자열 리터럴 및 변수를 사용하여 HTML 문자열을 작성하는 방법을 이미 알고 있음을 보여줍니다. 그래서 두 가지 개념을 결합하십시오 ... – nnnnnn

+0

그리고 배열에 어떤 유형의 데이터가 있습니까? –

답변

2

여기에 하나의 접근 방식 :

// using the same header code you provided 

var rows = ""; 
myArray.forEach(function(item, index) { 
    rows += "<tr>"; 
    rows += "<td class='key'><strong>" + item + "</strong></td>"; 
    rows += "</tr>"; 
}); 
return "<table>" + header + "<tbody>" + rows +"</tbody>" + "</table>"; 
0

할 수 있습니다 각 행을 만들고 더 큰 문자열로를 연결하는 myArray의를 통해 루프. 대신 텍스트 문자열을 구축

var rows = ""; 
for (var r = 0; r < myArray.length; r++) { 
    var row = "<tr>" + "<td class='key'><strong>" + myArray[r] + "</strong></td></tr>"; 
    rows = rows.concat(row); 
} 
0

나중에 HTML로 설정,이 같은 insertRow와 청소기 접근 방식을 사용하여 선택할 것 :

<table> 
    <thead> 
    <tr><td>A header</td></tr> 
    </thead> 
    <tbody> 
    </tbody> 
</table> 
<script type="text/javascript"> 
    var values = ['foo', 'bar', 'baz']; // Values to insert in table 

    // Get a reference to the <tbody> element 
    var tbody = document.querySelector('tbody'); 

    for (var i = 0; i < values.length; i++) { 
    // This appends a new row to the <tbody> and returns a reference 
    // to that element 
    var row = tbody.insertRow(); 

    // Similarly to append a cell to the row 
    var cell = row.insertCell(); 

    // Create a text node for the textual content and append it 
    // to the cell 
    var text = document.createTextNode(values[i]); 
    cell.appendChild(text); 
    } 
</script> 

this JSFiddle에서 알 수 있듯이.

관련 문제