在下面的代码中,它似乎没有在我已经拥有的三个“项目”中添加新的“项目”,我似乎无法找出原因:
HTML:
<div class ="formBlock menuDetails">
<p><span class="bookingName">Menu<span class="required">*</span></span><span class="bookingInput"><input type="text" name="menu"/></span></p>
<p><span class="bookingName">Item<span class="required">*</span></span><span class="bookingInput"><input type="text" name="item" /></span></p>
<p><span class="bookingName">Item<span class="required">*</span></span><span class="bookingInput"><input type="text" name="item"/></span></p>
<p><span class="bookingName">Item<span class="required">*</span></span><span class="bookingInput"><input type="text" name="item"></span></p>
<div class="appendMoreItems"></div>
<div class="addMoreItemsButton">
<a href="#" id="addItem">Add Item</a>
</div>
</div>
jQuery的:
$(document).ready(function (){
$('<div/>', {
'class' : 'menuDetails', html: getMenuHTMLDetails()
}).appendTo('#addMoreItemsButton');
$('#addItem').click(function () {
$('<div/>', {
'class' : 'extraMenuItem', html:getMenuHTMLDetails()
}).hide().appendTo('#menuDetails').slideDown('slow');
});
})
function getMenuHTMLDetails()
{
var len = $('.extraMenuItem').length;
var $clone = $('.menuDetails').clone();
$clone.find('[name=item]')[0].name="item"+len;
return $clone.html();
}
答案 0 :(得分:0)
这可能会对你有所帮助
$(document).ready(function (){
$('#addItem').click(function(){
var toClone = $('p:last').clone();
$('.appendMoreItems').append(toClone);
});
});
答案 1 :(得分:0)
您应该将其附加到.menuDetails
而非#menuDetails
(不存在)
$(document).ready(function () {
$('<div/>', {
'class': 'menuDetails',
html: getMenuHTMLDetails()
}).appendTo('#addMoreItemsButton');
$('#addItem').click(function () {
$('<div/>', {
'class': 'extraMenuItem',
html: getMenuHTMLDetails()
}).hide().appendTo('.menuDetails').slideDown('slow');
});
})
<强> Fiddle 强>
此外,如果您对标记进行少量更改,您将获得 this 输出
<div class="formBlock menuDetails">
<p><span class="bookingName">Menu<span class="required">*</span></span><span class="bookingInput"><input type="text" name="menu"/></span>
</p>
<p><span class="bookingName">Item<span class="required">*</span></span><span class="bookingInput"><input type="text" name="item" /></span>
</p>
<p><span class="bookingName">Item<span class="required">*</span></span><span class="bookingInput"><input type="text" name="item"/></span>
</p>
<p><span class="bookingName">Item<span class="required">*</span></span><span class="bookingInput"><input type="text" name="item" /></span>
</p>
<div class="appendMoreItems"></div>
</div>
<div class="addMoreItemsButton"> <a href="#" id="addItem">Add Item</a></div> <!-- do not clone the this everytime -->