2013-08-18 85 views
0

我嘗試獲取具有不同數量行的表格的單元格值(從php中的'while'循環生成)並對它們進行整形以適合在Google Chart API中。獲取HTML表格單元格中的InnerText並將其設置爲適合Google Chart API

下面是表:

<thead> 
    <tr> 
      <th>Sport/Month</th> 
     <th>January</th> 
     <th>February</th> 
     <th>March</th> 
    </tr> 
</thead> 

<tbody> 
    <tr> 
     <td>Tennis</td> 
     <td>Value Tennis.Jan</td> 
     <td>Value Tennis.Feb</td>  
     <td>Value Tennis.Mar</td> 
    </tr> 

    <tr> 
     <td>Football</td> 
     <td>Value Football.Jan</td> 
     <td>Value Football.Feb</td> 
     <td>Value Football.Mar</td> 
    </tr> 

    <tr> 
     <td>Sport_n</td> 
     <td>Value Sport_n.Jan</td> 
     <td>Value Sport_n.Feb</td> 
     <td>Value sport_n.Mar</td> 
    </tr> 
</tbody> 

我想塑造這樣的說法:

[ 
     ['Sport/Month','Tennis','Football','Sport_n'], 
     ['Jan',Value Tennis.Jan, Value Football.Jan, Value Sport_n.Jan], 
     ['Feb',Value Tennis.Feb, Value Football.Feb, Value Sport_n.Feb], 
     ['Mar',Value Tennis.Mar, Value Football.Mar, Value Sport_n.Mar] 
    ] 

爲了它在腳本集成:

https://code.google.com/apis/ajax/playground/?type=visualization#line_chart

我試着挑選從這裏的一些代碼,使用的innerText等:How to grab the values from an HTML table's cells using JavaScript

但我的JS知識是有限的,所以我不能得到想要什麼,我......

+3

你能不能產生,而不是因爲你已經在使用PHP生成HTML通過PHP js的變量? –

+0

你有什麼嘗試嗎?我的意思是我可以看到你嘗試過的代碼嗎? –

+0

@Jay Yup,也許我應該嘗試在PHP只...問題是,我有複雜的查詢和PHP循環來生成表和單元格的值,所以我想避免使用它們兩次,以保持頁面代碼儘可能清晰。 – Twimp

回答

0

如果您想要使用JS,這種方法可能有所幫助 -

/** 
* Pass this method table element, if you table id "t", use this method like - 
* getJSONArrayFromTable(document.getElementById("t")) 
* 
* @param tableElement 
* @returns {Array} 
*/ 
function getJSONArrayFromTable(tableElement) { 
    var json = []; 
    var rows = []; 

    Array.prototype.push.apply(rows, tableElement.tHead.rows); 
    for (var i = 0; i < tableElement.tBodies.length; i++) { 
     Array.prototype.push.apply(rows, tableElement.tBodies[i].rows); 
    } 

    for (var i = 0; i < rows.length; i++) { 
     json[i] = []; 
     for (var j = 0; j < rows[i].cells.length; j++) { 
      json[i].push(rows[i].cells[j].innerHTML); 
     } 
    } 
    return json; 

} 
0

只需爲每列創建數組,然後將它們變成行。

http://jsfiddle.net/N4Euz/

var $rows = $("table tr"), 
    len = $rows.length, 
    chartData = [], 
    cols = []; 


for(var i = 0; i < len; i++){ 
    cols[i] = []; 
    for(var y = 0; y < len; y++){ 
     cols[i].push(
      $rows.eq(y).find("td,th").eq(i).text() 
    ); 
    } 
} 

for(var i = 0; i < len; i++){ 
    chartData.push(
     cols[i] 
    ); 
} 

console.log(chartData); 
相關問題