2017-07-19 17 views
-1

剛學HTML + jQuery的如何把< tr >標籤,如果達到表

結束的意思是,每當我按下按鈕將其添加在第一列<td>標籤。 我想要做的是,如果我到達表格末尾或<th>,我只想把下一列。

$(".chkbox").click(function(){ 
    var value = $(this).val(), 
     $list = $("#tablebody") 

    if (this.click) { 
    $list.append("<td data-value='"+ value + "'>"+ value + "</td>") 
    $(this).remove() 
    } 
}) 

<table class="classytable" style="margin: 0px auto;">   
<caption>Сонгосон сонголт</caption>          
    <thead> 
     <tr id="colorfultr"> 
      <th scope="col">1</th> 
      <th scope="col">2</th> 
      <th scope="col">3</th> 
      <th scope="col">4</th> 
     </tr> 
    </thead> 
    <tbody id='tablebody'> 
    Inserted <td> goes in here 
    </tbody> </table> 
+0

請提供[mcve]以更好地解釋預期行爲 – charlietfl

+0

[https://i.stack.i mgur.com/FJFT4.png]這是表格的圖片,我想像頂部一樣展示。現在它像下一個連續加​​到1分第一列 –

+1

請發表您的當前HTML和預期輸出 –

回答

1

我你的問題的解釋是,上單擊要在表的正文中添加一個新的<td>元素,它應該被添加到,如果該表的當前最後一行行比標題行的單元格更少,否則應將其添加到新的空白行。因此,當你添加越來越多的單元格時,它們應該「換行」到新的行。

要實現,你可以做這樣的事情:

$(".chkbox").click(function() { 
 
    var value = $(this).val(), 
 
    $list = $("#tablebody"), 
 
    $lastRow = $list.find("tr").last(),   // get reference to last row 
 
    columnCount = $("#colorfultr th").length // get number of columns 
 
    
 
    if ($lastRow.length === 0 ||      // if there are no rows 
 
     $lastRow.find("td").length >= columnCount) { // or last row is already full 
 
     $lastRow = $("<tr></tr>").appendTo($list)  // add a new row 
 
    } 
 
    $lastRow.append("<td data-value='" + value + "'>" + value + "</td>") 
 
    //$(this).remove() 
 
})
th, td { width: 50px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<p>Clicking a button will add its text to the table:</p> 
 
<button class="chkbox" value="A">A</button> 
 
<button class="chkbox" value="B">B</button> 
 
<button class="chkbox" value="C">C</button> 
 

 
<table class="classytable" style="margin: 0px auto;"> 
 
    <caption>Сонгосон сонголт</caption> 
 
    <thead> 
 
    <tr id="colorfultr"> 
 
     <th scope="col">1</th> 
 
     <th scope="col">2</th> 
 
     <th scope="col">3</th> 
 
     <th scope="col">4</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody id='tablebody'> 
 
    </tbody> 
 
</table>

注意,在我的代碼片段演示目的我已經添加按鈕,並從你的代碼註釋掉$(this).remove()因爲如果按鈕被刪除點擊它很難繼續添加單元格...

+0

少於'​​'的行數要求會導致格式不完整的html。最好是有正確的號碼,並填寫下一個可用的單元格 –

+0

謝謝你,我想說什麼。不要擔心remove()。另一個函數將獲得該按鈕的值,以便在其他表格上顯示該值時,該按鈕可以按順序顯示給用戶。其某種測試 –

+0

我實現了我所嘗試的,我需要關閉這個答案或? –