我一直在試圖獲得一個與JQuery一起使用來添加或減少表單輸入字段的函數。我一直在用我發現的一個例子作爲出發點。使用JQuery添加或刪除表單元素
這是我到目前爲止有:
<script type="text/javascript">
$(function(){
// start a counter for new row IDs
// by setting it to the number
// of existing rows
var newRowNum = 2;
// bind a click event to the "Add" link
$('#addnew').click(function(){
// increment the counter
newRowNum += 1;
// get the entire "Add" row --
// "this" refers to the clicked element
// and "parent" moves the selection up
// to the parent node in the DOM
var addRow = $(this).parent().parent();
// copy the entire row from the DOM
// with "clone"
var newRow = addRow.clone();
// set the values of the inputs
// in the "Add" row to empty strings
$('input', addRow).val('');
$('name', addRow).val('os' + newRowNum);
// replace the HTML for the "Add" link
// with the new row number
$('td:first-child', newRow).html('<input type="hidden" name="on' + newRowNum + 'value="Email Address ' + newRowNum + '>Recipient');
// insert a remove link in the last cell
$('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>');
// loop through the inputs in the new row
// and update the ID and name attributes
$('input', newRow).each(function(i){
var newID = 'os' + newRowNum;
$(this).attr('id',newID).attr('name',newID);
});
// insert the new row into the table
// "before" the Add row
addRow.before(newRow);
// add the remove function to the new row
$('a.remove', newRow).click(function(){
$(this).parent().parent().remove();
return false;
});
// prevent the default click
return false;
});
});
</script>
的HTML如下:
<table>
<tr><td>
Email Addresses</td><td> </td>
<td> </td>
</tr>
<tr>
<td><input type="hidden" name="on2" value="Email Address 1"><a id="addnew" href="">Add</a></td><td><input name="os2" type="text" id="os2" value="" size="24" maxlength="60" /></td>
<td> </td>
</tr>
</table>
我感到困惑的是爲什麼,當我看網頁在瀏覽器中,我看到額外的輸入字段,但是當我查看源代碼時,無法找到額外字段的代碼。
有人能給我啓發嗎?
戴夫
爲IE開發工具欄+1,非常方便!我其實是在尋找類似的東西,但不知道我是如何錯過的。 – 2010-06-18 23:13:24