我正在嘗試找出一個函數,它可以在大約10個函數中進行迭代。使用jquery從另一個函數調用一個函數
我有一個函數創建服務來調用一個json url到我的函數中。這與主函數進行通信,在主函數下面調用服務函數,將相應url的選項用作啓動json請求的數據。請看下面;
var landp = {
getCountryCode : function(){
console.info('landp.GetCountryCode');
return window.location.pathname.match(/\/([a-zA-Z]{2})/)[1].toLowerCase();
},
Service : {
getBaseUrl : function(){
console.info('landp.Service.GetBaseUrl');
return sprintf("/%s/service", landp.getCountryCode())
},
callService : function(method, options){
console.info('landp.Service.CallService');
var url = sprintf("%s/%s", landp.Service.getBaseUrl(), method);
$.ajax({
url : url,
method : 'GET',
success : options.success,
error : options.error
})
},
getCategories : function(options){
landp.Service.callService('category', options);
},
getCategoryId : function(options){
landp.Service.callService('category/id/13', options);
},
getCategoryTopTen : function(options){
landp.Service.callService('category/name/top-ten', options);
},
getSeeMoreItems : function(options){
landp.Service.callService('see-more', options);
},
getPartnerOffers : function(options){
landp.Service.callService('partner-offers', options);
}
}
}
這工作好,你可以看到getCategoryTopTen將調用認爲我需要使用以獲得正確的項目,如item.name,item.description等等等等JSON數據的URL 。代碼如下。
landp.Service.getCategoryTopTen({
success : function(data){
$('#header').after('<div id="cat-sub-options"></div>');
$('#cat-sub-options').after('<div class="flexslider"><ul class="slides"></ul></div><div id="carousel-button" class="click"></div>');
$.each(data[0].items, function(i, item){
$('.flexslider .slides').append('<li class=""><h5>' + i + '</h5><a href="' + item.url + '"><img src="' + item.imageLargeUrl + '" alt="' + item.name + ' image" /><span>' + item.name + '</span></a></li>');
});
},
error : function(){
console.log("Error getting categories");
}
})
正如你可以看到上面的代碼工作,它將正確的信息拉入正確的元素等。目前約有10個類別,如;
getCategoryTopTen getCategoryHistoryHeritage getCategoryWheretogo getCategoryShopping getCategorySportyPeople
正如你可以看到每一個將被分配給在JSON文件中的類URL。
我想要解決的是我如何做到以上所有的類別例如我們有:landp.Service.getCategoryTopTen與下面的代碼,而不是寫在每個類別itout我可以傳遞一個變量,而不是每個功能其他明智的我將不得不做每個類別的這些JSON調用。
任何幫助將不勝感激。
謝謝, 馬克
請使用簡單的字符串與'+'運算符連接,而不是'sprintf'函數(它在內部執行相同的操作,甚至在使用正則表達式替換等時)。 JavaScript是一種高級語言:-) – Bergi