[英]Adding rows and columns to an HTML table using jQuery
我正在使用jquery向表中動態添加列和行。
我遇到的問題是我要使用以下代碼添加行:
$('#colorgrid').append("<tr id='Row2' class='input-row'><td><input type='text' name='shade' placeholder='shade'/></td><td ><input type='checkbox' name='asdf'/></td><td ><input type='checkbox' name='shade'/></td><td ><input type='checkbox' name='color'/></td></tr>")
因此,在我添加一列然后添加一行之后,它缺少一個復選框。 請參閱以下屏幕截圖:
理想情況下,無論何時添加新行,我都希望它用復選框填充很多列,並用列名填充復選框的name
屬性。
題
我如何以這種方式添加新行,使其真正具有動態性,並且不對行的內容進行硬編碼。 它應該用復選框填充所有列,並根據columnheader命名它們。
您應該查看JQuery的Clone函數 。 您可以克隆最后一行或第一行,而無需實際對要添加的元素進行硬編碼。 這將復制所有元素,包括新列。
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
$('.hello').clone().appendTo('.container');
這應該產生
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
<div class="hello">Hello</div>
</div>
在執行appendTo
之前,您可以自行修改每個元素的name
, id
和value
(如果需要)。 您也可以使用jQuery。 查找每個input
元素:
newRow.find('input').each(function () {
var $inputElem = $(this);
$inputElem.attr('id', 'newId'); //change this to something more dynamic
$inputElem.attr('name', 'newName'); //change this to something more dynamic
}
Andy的答案更干凈,您可能需要在修改其中的元素時做到這一點。 但是,如果不是“復制但不同”的情況,而更多的是“復制具有某些部分的新行”,則此fork可能會有幫助 。
這里的技術涉及創建一個新行,然后使用jQuery的each方法 (在此指定以在表中選擇#Row1 th:not(.space)
遍歷每個所需的表頭,即“ #Row1
中的頭#Row1
”。 t .space
“),使用jQuery的修剪使其內部文本沒有多余的空格(換行符,縮進),然后附加一個新單元格並以該值作為每個輸入的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.