【问题标题】:how to call another function from a different file using eval in jquery如何在 jquery 中使用 eval 从不同的文件调用另一个函数
【发布时间】:2015-03-13 13:58:18
【问题描述】:

所以基本上我有一个 app.js 文件,它有一个可以传递参数的函数

而且我还有更多的 js 文件,例如 posts.js、comment.js 然后我可以做 app.init('posts');

然后我找到文件,使用 getscript 获取它,但现在我需要调用该文件。

这是我的代码

init:function(file){
        getfile = file;
        if($.inArray(getfile+'.js', modular_array)!==-1){
              $.getScript("js/modulars/"+getfile+'.js', function(data){
                  console.log(eval(getfile)["init"]); // this does not! why
                  //console.log(posts.init()); // this works
              });
        } else {
            console.log('not it');
        }
    }

【问题讨论】:

    标签: javascript jquery eval getscript


    【解决方案1】:

    getScript 自动加载并运行脚本文件——您无需手动执行:

    init:function(file){
            getfile = file;
            if($.inArray(getfile+'.js', modular_array)!==-1){
                  $.getScript("js/modulars/"+getfile+'.js');
            } else {
                console.log('not it');
            }
        }
    

    如果你确实想调用脚本定义的一些初始化函数,你可以直接调用它,你发现了:posts.init()

    代码eval(getfile) 不起作用,因为getfile 是一个文件名。 eval 需要一个包含 Javascript 代码的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多