У меня проблема с циклом с функцией.load внутри цикла. Я передаю значение из списка, в котором указано количество создаваемых разделов. Я использую Mustache для загрузки шаблона из отдельного файла. Это должно создать количество разделов в списке, но все, что у меня получается, это последний раздел, созданный и ни один из остальных. После кода через отладчик функция.load не хочет запускаться до последнего прохода цикла. Список на. (Изменение) выглядит следующим образом:
$(document).on('change', '#SCTotSections', function () {
var sectNumToCreate = parseInt($('#SCTotSections :selected').val(), 10);
var startNumSections = parseInt(startSectNum, 10);
var currentAddSection = startNumSections + 1;
var postTo = '#writeToTest';
if (sectNumToCreate < startNumSections)
{
if (startNumSections != sectNumToCreate )
{
var myNode = document.getElementById("S" + startNumSections)
myNode.remove();
//while (myNode.firstChild) {
// myNode.removeChild(myNode.firstChild);
//}
startSectNum = startSectNum - 1;
startNumSections = startNumSections - 1;
}
}
else if (sectNumToCreate > startNumSections)
{
while (startNumSections != sectNumToCreate)
{
var data = {
section: currentAddSection
};
$("#templates").load("../SCSectionTemplate #SCSectionTemplate", function () {
var template = document.getElementById('SCSectionTemplate').innerHTML;
var output = Mustache.render(template, data);
$(postTo).html(output);
});
currentAddSection = currentAddSection + 1;
startSectNum = startSectNum + 1;
startNumSections = startNumSections + 1;
}
}
});
Есть две проблемы, которые я вижу.
data
в цикле не является правильным (см Создания замыкания в циклах: Частая ошибка и Javascript замыкания внутри циклы - простой практический пример).Поэтому постарайтесь
$(document).on('change', '#SCTotSections', function () {
var sectNumToCreate = parseInt($('#SCTotSections :selected').val(), 10);
var startNumSections = parseInt(startSectNum, 10);
var currentAddSection = startNumSections + 1;
var postTo = '#writeToTest';
if (sectNumToCreate < startNumSections) {
if (startNumSections != sectNumToCreate) {
var myNode = document.getElementById("S" + startNumSections)
myNode.remove();
//while (myNode.firstChild) {
// myNode.removeChild(myNode.firstChild);
//}
startSectNum = startSectNum - 1;
startNumSections = StartNumSections - 1;
}
} else if (sectNumToCreate > startNumSections) {
//clear the container
$(postTo).empty('');
while (startNumSections != sectNumToCreate) {
var data = {
section: currentAddSection
};
//use a local closure for the data variable
(function (data) {
$("#templates").load("../SCSectionTemplate #SCSectionTemplate", function () {
var template = document.getElementById('SCSectionTemplate').innerHTML;
var output = Mustache.render(template, data);
//keep appending new items from the loop
$(postTo).append(output);
});
})(data);
currentAddSection = currentAddSection + 1;
startSectNum = startSectNum + 1;
startNumSections = startNumSections + 1;
}
}
});