javascript - 如何制作动态函数?

标签 javascript jquery function loops dynamic-function

我有 10 个这样的函数:

function instagram_ajax(){
    return ajaxRequest('search/instagramid', 'instagramid').then(
        function(res) {
            var imgStatus = res[1].length > 0 ? "checked_successfully.png" : "checked_noRes.png";
            $('.option_name_instagramid + td').html("<img src='img/" + imgStatus + "' />")

            optionsRes['instagramid'] = res[1];

        }, function(err){
            $('.option_name_instagramid + td').html("<img src='img/warning.png' />")
        }
    );
}

function googleplus_ajax(){
    return ajaxRequest('search/googleplusid', 'googleplusid').then(
        function(res) {
            var imgStatus = res[1].length > 0 ? "checked_successfully.png" : "checked_noRes.png";
            $('.option_name_googleplusid + td').html("<img src='img/" + imgStatus + "' />")

            optionsRes['googleplusid'] = res[1];

        }, function(err){
            $('.option_name_googleplusid + td').html("<img src='img/warning.png' />")
        }
    );
}

.
.
.

如您所见,这些功能几乎是相同的,只是单词 instagramgoogleplus 有所不同。我还有一个包含所有这些名称的数组:

var parts = ['instagram', 'googleplus', 'linkedin', 'facebook', ...];

现在我想知道,是否可以动态地创建这些数组?我的意思是,将一个基于变量的函数放入循环中并使用该数组来生成所有这些函数?这样的事可能吗?

最佳答案

制作一个包装函数

function ajax(str) {
  return function() {
    return ajaxRequest('search/'+str+'id', ''+str+'id').then(
        function(res) {
            var imgStatus = res[1].length > 0 ? "checked_successfully.png" : "checked_noRes.png";
            $('.option_name_'+str+'id + td').html("<img src='img/" + imgStatus + "' />")

            optionsRes[str+'id'] = res[1];

        }, function(err){
            $('.option_name_'+str+'id + td').html("<img src='img/warning.png' />")
        }
    );
  }
}

var instagram_ajax = ajax('instagram');
var googleplus_ajax = ajax('googleplus');

或者针对您的情况

var parts = ['instagram', 'googleplus', 'linkedin', 'facebook'];

var funcs = {};
for (var i = 0; i < parts.length; i++)
  funcs[parts[i]] = ajax(parts[i]);

// now u do
funcs.instagram()

关于javascript - 如何制作动态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46871339/

相关文章:

javascript - 如何验证背景(css)图像是否已加载?

javascript - 注入(inject)器已经创建。无法注册模块

javascript - Angular - 在 ng-repeat 内添加赞成按钮

c - 为什么 strlen 的参数是 "const"?

javascript - MongoDB 按小时分组

javascript - jsSocials 分享到 Pinterest image_url 错误

javascript - 在 Canvas 中绘制图像会删除填充背景

javascript - 显示隐藏 Div 的 Angular 方式类似于选项卡但没有选项卡

python 现在,接下来,n 次迭代

objective-c - Objective C 类方法与 C 函数