2013-12-12 2 views
1

테이블에서 데이터를 가져와 배열에 저장해야합니다. 테이블의 각 행은 배열 내의 새로운 배열이어야합니다. 기본적으로 HTML은 다음과 같습니다 요법배열 배열 내에서 테이블 데이터 저장소 찾기

<table id="contactlisttable"> 
    <tr> 
     <th>Name</th> 
     <th>Title</th> 
     <th>Phone</th> 
    </tr> 
    <tr> 
     <td class="contactlist contactlistlastfirst">Joey</td> 
     <td class="contactlist contactlisttitle">webdesigner</td> 
     <td class="contactlist contactlistphone">5555555</td> 
    </tr> 
    <tr> 
     <td class="contactlist contactlistlastfirst">Anthony</td> 
     <td class="contactlist contactlisttitle">webdesigner</td> 
     <td class="contactlist contactlistphone">5555555</td> 
    </tr> 
</table> 

... 여기

내 코드

jQuery(document).ready(function(){ 
    $(function(){ 
     var $table = $("#contactlisttable"), 
     $headerCells = $table.find("tr th"), 
     $myrows = $table.find("tr"); // Changed this to loop through rows 

     var headers = [], 
      rows = []; 

     $headerCells.each(function() { 
      headers[headers.length] = $(this).text(); 
     }); 

     $myrows.each(function() { 
      $mycells = $myrows.find("td.contactlist"); // loop through cells of each row 
      cells = [] 
      $mycells.each(function() { 
       cells.push($(this).text()); 
      }); 
      if (cells.length > 0) { 
       rows.push(cells); 
      } 
     }); 
     console.log(headers); 
     console.log(rows); 
    }); 
}); 

내 현재 코드 끈다

[["Waddell, Joey", "webdesigner", "", 15 more...], ["Waddell, Joey", "webdesigner", "", 15 more...], 

원하는 출력이 될 것입니다 :

["Name","Title","Phone"] 
[["Joey","webdesigner","555555"] 
["Anthony","webdesigner","555555"]] 
+0

여기에 큰 내 코드 http://jsfiddle.net/joeylobo/m4dW6/ – user2882684

답변

0

나는이 간단 할 수 있다고 생각 :

Live Demo

JS에게

$(function(){ 
    var results = []; 
    var row = -1; 
    $('#contactlisttable').find('th, td').each(function(i, val){ 
     if(i % 3 === 0){ //New Row? 
      results.push([]); 
      row++;//Increment the row counter 
     } 
     results[row].push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)  
    }); 
    console.log(results); 
}); 

편집

여기에 더 좋은 해결책이 있습니다 (IE9 + 호환). 그것은 이전의 솔루션과 달리 가변 행 길이를 고려합니다.

Live Demo

JS

//IE9+ compatable solution 
$(function(){ 
    var results = [], row; 
    $('#contactlisttable').find('th, td').each(function(){ 
     if(!this.previousElementSibling){ //New Row? 
      row = []; 
      results.push(row); 
     } 
     row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)  
    }); 
    console.log(results); 
}); 
+0

의 작업 예입니다! .innerHTML 대신 .text()를 사용할 수있어서 html이 없습니까? – user2882684

+0

물론 this.innerText ||를 사용하더라도'this.innerHTML'을'$ (this) .text()'로 변경하십시오. this.textContent'는'this'의 jQuery 객체에 대한 불필요한 변환을 제거하고 firefox와의 호환성을 유지하기 때문에보다 성능이 좋습니다. –

+0

ok 좋아 보이는데, 5 행을 이해하는 데 문제가 있습니다. 이것은 내부 배열에 tr을 추가하는 것입니다. – user2882684

관련 문제