伙计,我一直在用这个问题崩溃我的火狐lol。
$("#add-contact-to-prospect-file").live("click", function(e) {
var $npac = $("#new-prospect-add-contacts"),
addVal = parseInt($("#new-prospect-additional-contact").val(), 10) + $npac.find('li').length;
while ($npac.find('li').length < addVal) {
var nLi = $('<li><span>Contact ' + parseInt($npac.find('li').length + 1, 10) + '</span></li>').css('display', 'none');
$npac.append(nLi);
}
$npac.find('li:hidden').each(function(i, obj) {
$(obj).delay((i + 1) * 150).fadeIn(600);
});
$npac.find('li').each(function(j, obj) {
var fieldsetCount = $('#steps').children().length;
while(fieldsetCount < $npac.find('li').length){
$('#new-prospect-form').append('<fieldset>').addClass('step');
fieldsetCount + 1;
console.log(fieldsetCount);
}
console.log(j);
});
slideForm();
return false;
});
上半部分就像魅力一样,但是当我接触逻辑将一个字段集附加到我的表单时,它会像疯狂的页面一样循环。
基本上,用户会添加X个联系人,并通过<li>
将其附加到列表中,所以它看起来像这样
<li>Contact 1</li>
<li>Contact 2</>
..etc..
然后我希望将一个字段集添加到我的表单中,每个<li>'s
将<li>
的值传递给<legend>
答案 0 :(得分:2)
尝试此更改:
$npac.find('li').each(function(j, obj) {
var fieldsetCount = $('#steps').children().length;
var licount = $npac.find('li').length;
while(fieldsetCount < licount){
$('#new-prospect-form').append('<fieldset>').addClass('step');
console.log(fieldsetCount);
licount--;
}
console.log(j);
});
答案 1 :(得分:1)
在while
循环中:
$npac.find('li').each(function(j, obj) {
var fieldsetCount = $('#steps').children().length;
while(fieldsetCount < $npac.find('li').length){
$('#new-prospect-form').append('<fieldset>').addClass('step');
console.log(fieldsetCount);
}
console.log(j);
});
我没有看到该循环终止的任何方法。如果它执行一次,它将重复执行,因为fieldsetCount
和$npac.find('li').length
未在循环体内修改。
答案 2 :(得分:1)
你做了很多追加和循环太多次了。
// Cache these selectors because they arn't going to change.
var $npac = $("#new-prospect-add-contacts"),
$npf = $('#new-prospect-form');
$npac_input = $("#new-prospect-additional-contact");
$("#add-contact-to-prospect-file").live("click", function(e) {
// Prevent default rather than return false
// Lets the event bubble up the DOM
e.preventDefault();
var total = $npac.find('li').length,
addVal = parseInt($npac_input.val(), 10),
lis = [],
fieldsets = [];
// Push all the new elements in to the correct array
for (var i = 1; i <= addVal; i++) {
var text = 'Contact ' + (total + i);
lis.push('<li style="display:none;"><span>' + text + '</span></li>');
fieldsets.push('<fieldset class="step"><legend>' + text + '</legend></fieldset>');
}
// Then only append once.
$(lis.join('')).appendTo($npac)
// Then loop over all the new hiddden elements
.each(function(i, obj) {
$(obj).delay((i + 1) * 150).fadeIn(600);
});
// add all the fieldsets
$(fieldsets.join('')).appendTo($npf);
//slideForm();
});