我正在尝试找出一个函数,它可以在大约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