我正在尝试在 javascript 中编写一个迭代大约 10 个函数的函数。
我有一个函数可以创建服务来将 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 将调用一个 url,其中包含我需要用来获取正确项目(例如 item.name、item.description 等)的 json 数据。其代码如下;
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 个类别,例如;
获取类别前十名 获取类别历史遗产 获取类别去哪里 获取类别购物 获取类别运动人物
如您所见,每个类别都会被分配给 json 文件中的一个类别 url。
我想要解决的是如何对所有类别执行上述操作,例如我们有: landp.Service.getCategoryTopTen ,使用下面的代码而不是在每个类别上编写它,我可以将变量传递给每个类别吗否则我将不得不对每个类别执行每个 json 调用。
任何帮助将不胜感激。
谢谢, 标记
最佳答案
我不确定我完全理解问题所在,但使用 [] 表示法访问 JavaScript 子项可能会让您受益匪浅。例如,而不是打电话
landp.Service.getCategoryTopTen()
你可以调用 landp.Service["getCategoryTopTen"]()
然后可以将其拉出来,这样你就会得到类似的东西:
var category="TopTen"
var method="getCategory"+category
land.Service[method](...)
然后你可以围绕它包装你的逻辑来迭代或以其他方式自动化。
关于javascript - 使用 jquery 从另一个函数调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12500866/