【发布时间】:2009-05-13 07:39:45
【问题描述】:
(希望这不会重复;第二次尝试提交此问题)
我正在制作一个表单,希望用户能够在其中添加数量不定的联系人(姓名和电话号码)。我只想显示这些表单字段的一行开始,并允许用户单击一个元素,该元素将添加初始行的副本(当然是空的,并且在返回控制器时使用更新的 id 来操作该数据(ASP.NET MVC 应用程序)。
我找到了一些使用 jQuery 库 1.2.x 版本的示例,但我似乎无法让它们中的任何一个与 1.3.2 一起使用。该问题与 $.clone() 方法有关。当我在选择器/元素上调用此方法时,页面会完全刷新,并且会为用户呈现一个干净的表单。
我一直在使用的当前示例(来自http://devblog.jasonhuck.com/assets/infiniteformrows.html)看起来像:
桌子-
<table id="tabdata">
<thead>
<tr>
<th>Row</th>
<th>Cell 1</th>
<th>Cell 2</th>
<th>Cell 3</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><a id="addnew" href="">Add</a></td>
<td><input id="n0_1" name="n0_1" type="text" /></td>
<td><input id="n0_2" name="n0_2" type="text" /></td>
<td><input id="n0_3" name="n0_3" type="text" /></td>
<td></td>
</tr>
</tbody>
</table>
脚本 -
<script type="text/javascript">
$(function() {
var newRowNum = 0;
$('#addnew').click(function() {
newRowNum++;
var addRow = $(this).parent().parent();
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html(newRowNum);
$('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>');
$('input', newRow).each(function(i) {
var newID = newRowNum + '_' + i;
$(this).attr('id', newID).attr('name', newID);
});
addRow.before(newRow);
$('a.remove', newRow).click(function() {
$(this).parent().parent().remove();
return false;
});
return false;
});
});
</script>
当方法声明“var newRow = addRow.clone();”时,页面会重新加载。不知道为什么,但是针对早期的 jQuery 版本运行脚本,它工作得很好。如果我能提供帮助,我宁愿不要退回版本。
有什么想法吗?有没有更好的方法来解决这个问题?它应该很简单,但事实证明它比我希望使用我选择的库更乏味。
【问题讨论】:
标签: javascript jquery asp.net-mvc