所有
我有一大堆HTML用作JQuery .clone()
方法的源代码。 HTML块中包含一个“删除”图标,点击后该图标应删除复制的HTML块,但不会。
我可能没有正确选择复制的元素,但我不确定。
由于
以下是代码:
HTML
<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="formColumn1"><label for="sponsorclubname1">Sponsor club name 1:</label></span>
<span class="formColumn2"><input type="text" id="cosponsorcontact" name="cosponsorcontact" placeholder="Name" title="Co-sponsor contact" /></span>
<span class="formColumn3"><input type="text" id="cosponsoremail" name="cosponsoremail" placeholder="Email" title="Co-sponsor email" /></span>
<span class="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="js-add-cosponsor-hyperlink">+ cosponsor</span>
</p>
</form>
<!-- Start Add Co-Sponsor Row Template -->
<div style="display:none">
<div id="cosponsorsTemplate">
<span class="formColumn1"><label>Sponsor club name</label></span>
<span class="formColumn2"><input type="text" id="cosponsorcontact" name="cosponsorcontact" placeholder="Name" title="Co-sponsor contact" /></span>
<span class="formColumn3"><input type="text" id="cosponsoremail" name="cosponsoremail" placeholder="Email" title="Co-sponsor email" /></span>
<span class="formColumn4"><input type="text" id="cosponsorphone" name="cosponsorphone" placeholder="Phone" title="Co-sponsor phone" /><a class="icon delete"></a></span>
</div>
</div>
<!-- End Add Co-Sponsor Row Template -->
JS
$(document).ready(function () {
var uniqueId = 1;
$(function () {
$('.js-add-cosponsor-hyperlink').click(function () {
var copy = $("#cosponsorsTemplate").clone(true).appendTo("#addCosponsorSection").hide().fadeIn('slow');
var cosponsorDivId = 'cosponsors_' + uniqueId;
copy.attr('id', cosponsorDivId);
var deleteLink = $(this).find('.icon delete');
deleteLink.click(function () {
copy.fadeOut(300, function () { $(this).remove(); }); //fade out the removal
});
$('#' + cosponsorDivId).find('input').each(function () {
$(this).attr('id', $(this).attr('id') + '_' + uniqueId);
$(this).attr('name', $(this).attr('name') + '_' + uniqueId);
});
uniqueId++;
});
});
});
答案 0 :(得分:2)
您当前正在尝试在+ cosponsor
链接中选择删除图标。您需要选择模板元素的实际副本。
通过将复制的元素定义为自己的变量,我获得了成功。这样,您可以选择元素中复制的元素。
var thecopy=copy.attr('id', cosponsorDivId);
我还将click()
处理程序替换为on()
:
var deleteLink = thecopy.find('a.icon.delete');
deleteLink.on('click',function () {
copy.fadeOut(300, function () { $(this).remove(); }); //fade out the removal
});
答案 1 :(得分:2)
改变这个:
var deleteLink = $(this).find('.icon delete');
到此:
var deleteLink = copy.find(".icon.delete");