2014-04-28 84 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