2016-01-22 103 views
-1

誰能告訴我如何創建該表與HTML DOM的JavaScript。我試圖使通過ID查找元素,並添加到現有<table class="overflow-y"></table>標籤的功能。但是我找不到一種查看我生成的html代碼的方法,並且不知道我要出錯的地方。HTML表的創建與DOM

<table id="mytable" class="overflow-y"> 
    <thead> 
    <tr> 
     <th>corner</th><th>header1</th><th>header2</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <th>row1</th><td>1-1</td><td>1-2</td> 
    </tr><tr> 
     <th>row2</th><td>2-1</td><td>2-2</td> 
    </tr><tr> 
     <th>row3</th><td>3-1</td><td>3-2</td>< 
    </tr><tr> 
     <th>row4</th><td>4-1</td><td>4-2</td> 
    </tr><tr> 
     <th>row25</th><td>5-1</td><td>5-2</td 
    </tr> 
    </tbody> 
</table> 
+0

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild? – Shyju

+0

這是你正在尋找[dinamyc行]什麼(https://jsfiddle.net/eldien/v2t3g1r2/) –

+0

動態行幾乎是我要找的@OmarYafer但我列的動態數量,以及 – Jon

回答

1

我在這個Fiddle中所做的例子如何?

考慮這個HTML結構

<table id="myTable" class="table"> 
    <tbody></tbody> 
</table> 
<hr> 
<button class="button" id="addRow">Row +</button> 
<button class="button" id="addColumn">Column + </button> 

在每個按鈕添加列和行的HTML。

並與您控制生成的行和列的方式,以下的jQuery功能。

(function($){ 
    $(document).ready(function(){ 
    var myTable = $('#myTable'); 
    addRows(myTable); 
    addColumns(myTable); 

    }); 

    function addRows(table){ 
    $('#addRow').click(function(){ 
     var lastRow = $('#myTable > tbody > tr:last-child'); //fetch last row so you can copy it. You will need to find a way to copy only the structure. 


     if(lastRow.length > 0){ 
     table.append(lastRow.clone()); //Append a copy of the last row to the table 
     } 
     else{ 
     table.append($('<tr></tr>')); //create an empty row 
     } 
    }); 
    } 

    function addColumns(table){ 
    $('#addColumn').click(function(){ 
      var rows = $('#myTable > tbody > tr'); //Get all rows 
     rows.append($('<td>Column</td>')); //Append a td to all rows in the body 
    }); 
    } 
})(jQuery); 

在你的最終代碼,你將需要:列

  • 控制數量,讓你鴕鳥政策得到一個奇怪的表。
  • 添加的輸入,這樣就可以添加到第一個

希望它可以幫助你入門。

+0

這看起來很不錯,我從來沒有使用JQuery的,但我得做了一些教程然後去編輯代碼。我想我應該爲函數添加行數/列數的參數,以便在html頁面加載時建立表格。非常感謝。 – Jon