我正在尝试克隆一大块表单元素HTML并将其添加到DOM中。添加和删除工作正常,但块中新添加的输入元素没有获得唯一的ID和名称。
我无法为“name”或“id”创建唯一的属性值。
出于某种原因我的选择器$('#myForm div:last').find('input').each(function(){...}
没有抓住这些。
<script type="text/javascript">
var uniqueId = 1;
$(function() {
$('.hyperlink').click(function() {
var copy = $("#cosponsorsTemplate").clone(true).appendTo("#addCosponsorSection");
var cosponsorDivId = 'cosponsors_' + uniqueId;
copy.attr('id', cosponsorDivId );
var deleteLink = $('<span class="t_formColumn5"><a class=\"icon delete\"></a></span><div class="clear"></div>');
deleteLink.appendTo(copy);
deleteLink.click(function(){
copy.remove();
});
$('#myForm div:last').find('input').each(function(){
$(this).attr('id', $(this).attr('id') + '_'+ uniqueId);
$(this).attr('name', $(this).attr('name') + '_'+ uniqueId);
});
uniqueId++;
});
});
</script>
</head>
<body>
<div id="container">
<h2>Sponsors Section</h2>
<form action="" id="myForm">
<div id="addCosponsorSection" style="width:900px; margin-left:12px;">
<div id="cosponsors">
<span class="t_formColumn1"><label for="sponsorclubname1">Sponsor club name 1:</label></span>
<span class="t_formColumn2"><input type="text" id="cosponsorcontact" name="cosponsorcontact" placeholder="Name" title="Co-sponsor contact" /></span>
<span class="t_formColumn3"><input type="text" id="cosponsoremail" name="cosponsoremail" placeholder="Email" title="Co-sponsor email" /></span>
<span class="t_formColumn4"><input type="text" id="cosponsorphone" name="cosponsorphone" placeholder="Phone" title="Co-sponsor phone" /></span>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<p><span class="hyperlink">+ cosponsor</span></p>
</form>
<!-- Start Template to Clone -->
<span style="display:none">
<div id="cosponsorsTemplate">
<span class="t_formColumn1"><label for="sponsorclubname1">Sponsor club name</label></span>
<span class="t_formColumn2"><input type="text" id="cosponsorcontact" name="cosponsorcontact" placeholder="Name" title="Co-sponsor contact" /></span>
<span class="t_formColumn3"><input type="text" id="cosponsoremail" name="cosponsoremail" placeholder="Email" title="Co-sponsor email" /></span>
<span class="t_formColumn4"><input type="text" id="cosponsorphone" name="cosponsorphone" placeholder="Phone" title="Co-sponsor phone" /></span>
</div>
</span>
<!-- End Template to Clone -->
</body>
</html>
答案 0 :(得分:1)
答案 1 :(得分:1)
你的选择器$('#myForm div:last')
抓住<div class="clear"></div>
为什么不只是使用你已经拥有的copy
对象来引用新的div?