【发布时间】:2009-10-14 06:27:37
【问题描述】:
我一直在尝试使用 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>
我很困惑的是,为什么当我在浏览器中查看页面时,我看到了额外的输入字段,但当我查看源代码时,却找不到额外字段的代码。
有人可以告诉我吗?
戴夫
【问题讨论】: