2014-04-28 43 views
0

我在循环内部遇到了一个循环使用.load函数的问题。我从列表框传入一个值,这表示要创建的部分的数量。我正在使用Mustache从单独的文件加载模板。这应该创建列表框中的部分数量,但所有我最终创建的部分是其中的最后一部分。在通过调试器的代码之后,.load函数不希望在循环的最后一次传递之前触发。 (更改)列表框如下:。循环内的.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; 


    } 
} 
}); 

回答

1

有两个问题,我可以看到。

所以尽量

$(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; 


     } 
    } 
}); 
+0

非常感谢这一点。这工作。我还有很多东西需要学习,所以我们非常感谢您的帮助。 – AndyRow123