我們在開發項目中或多或少都會存在問題。這個時候我們需要動態添加和刪除表行,今天就是錯新技術頻道小編為大家帶來的jquery.html" target="_blank">jquery實現增加刪除行的方法,希望能幫到你。
最近做一個投票管理的模塊,需要添加問題選項,為了方便,就簡單地實現了表格行的添加、刪除。
注:需引入jquery.js
先上效果圖:(form中默認有4行)

表單代碼:
復制代碼 代碼如下:
<div class="oz-form-fields"? style="width:450px;padding-top: 5px">?
??? <table cellpadding="0" cellspacing="0" style="width:450px;" id="optionContainer">?
??????? <tr id="option0">??
??????????? <td class="oz-form-topLabel">所屬問題?
??????????????? <c:if test="${questionType=='radio'}">(單選)</c:if>?
??????????????? <c:if test="${questionType=='checkbox'}">(復選)</c:if>:?
??????????? </td>?
??????????? <td class="oz-property" >?
??????????????? ${question}?
??????????? </td>?
??????????? <td></td>?
??????? </tr>?
??????? <tr id="option1">??
??????????? <td class="oz-form-topLabel">選項1:</td>?
??????????? <td class="oz-property" >?
??????????????? <input type="text"? style="width:300px">?
??????????? </td>?
??????????? <td></td>?
??????? </tr>?
??????? <tr id="option2">??
??????????? <td class="oz-form-topLabel">選項2:</td>?
??????????? <td class="oz-property" >?
??????????????? <input type="text"? style="width:300px" >?
??????????? </td>?
??????????? <td></td>?
??????? </tr>?
??????? <tr id="option3">??
??????????? <td class="oz-form-topLabel">選項3:</td>?
??????????? <td class="oz-property" >?
??????????????? <input type="text"? style="width:300px">?
??????????? </td>?
??????????? <td></td>?
??????? </tr>?
??????? <tr id="option4">??
??????????? <td class="oz-form-topLabel">選項4:</td>?
??????????? <td class="oz-property" >?
??????????????? <input type="text"? style="width:300px">?
??????????? </td>?
??????????? <td></td>?
??????? </tr>?
??? </table>?
??? <div style="text-align: center;">?
??????? <a href="#" onclick="addRow()">添加一行</a>?
??? </div>?
</div>
?
JS代碼:
復制代碼 代碼如下:
var rowCount=4;? //行數默認4行?
??
//添加行?
function addRow(){?
??? rowCount++;?
??? var newRow='<tr id="option'+rowCount+'"><td class="oz-form-topLabel">選項'+rowCount+':</td><td class="oz-property" ><input type="text"? style="width:300px"></td><td><a href="#" onclick=delRow('+rowCount+')>刪除</a></td></tr>';?
??? $('#optionContainer').append(newRow);?
}?
?
//刪除行?
function delRow(rowIndex){?
??? $("#option"+rowIndex).remove();?
??? rowCount--;?
}
?
需要注意的是,表單的<tr>中需要定義ID,如果默認有行的,就如代碼所示有規律地定義好ID,這樣可以方便添加一行的時候定義新行ID。
JS中要定義一個行數變量,因為我的表單中默認了4行(第一行,即id='option0'這行可以不用管),所以JS中定義的rowCount默認為4.
OK,完事。就如此的簡單。
另外,如果需要在指定位置增加行,需要這么寫
復制代碼 代碼如下:
$("#tab tr").eq(-2).after("<tr style='border:none;'><td style='width: 120px;border:none;' align='right'><strong>關鍵詞名稱:</strong></td><td style='width: 225px;border:none;'><input type='text' name='name' id='smsName' style='width: 135px;'/> <span class='red'>?*</span></td></tr>");
?
-2就是在倒數第二個tr后面增加行。
tab是表格的id
今天錯新技術頻道小編帶來了jquery實現增加刪除行的方法,大家學習的怎樣了呢?其實大家可以根據自己項目的需要,對原代碼進行改進哦。