我得到了一个字符串:

settings.functionName + '(' + t.parentNode.id + ')';

我想翻译成一个函数调用,像这样:

clickedOnItem(IdofParent);

当然,这必须用JavaScript来完成。当我在设置上做警报时。functionName + '(' + t.parentNode.id + ')';似乎每件事都是正确的。我只需要调用它转换成的函数。

传说:

settings.functionName = clickedOnItem

t.parentNode.id = IdofParent

当前回答

因为我讨厌eval,而且我不是一个人:

var fn = window[settings.functionName];
if(typeof fn === 'function') {
    fn(t.parentNode.id);
}

Edit: In reply to @Mahan's comment: In this particular case, settings.functionName would be "clickedOnItem". This would, at runtime translate var fn = window[settings.functionName]; into var fn = window["clickedOnItem"], which would obtain a reference to function clickedOnItem (nodeId) {}. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(t.parentNode.id), which equals clickedOnItem(t.parentNode.id), which was what the OP wanted.

更完整的例子:

/* Somewhere: */
window.settings = {
  /* [..] Other settings */
  functionName: 'clickedOnItem'
  /* , [..] More settings */
};

/* Later */
function clickedOnItem (nodeId) {
  /* Some cool event handling code here */
}

/* Even later */
var fn = window[settings.functionName]; 
/* note that settings.functionName could also be written
   as window.settings.functionName. In this case, we use the fact that window
   is the implied scope of global variables. */
if(typeof fn === 'function') {
    fn(t.parentNode.id);
}

其他回答

虽然我喜欢第一个答案,我讨厌eval,但我想补充的是,还有另一种方法(类似于eval),所以如果你可以绕过它而不使用它,你最好这样做。但在某些情况下,你可能想在ajax调用之前或之后调用一些javascript代码,如果你在自定义属性中有这些代码而不是ajax,你可以使用:

    var executeBefore = $(el).attr("data-execute-before-ajax");
    if (executeBefore != "") {
        var fn = new Function(executeBefore);
        fn();
    }

或者最终将它存储在函数缓存中,如果您可能需要多次调用它。

再次强调,如果有其他方法,不要使用eval或这个方法。

在使用CommonJS规范的javascript中,比如node.js,你可以做我下面展示的事情。这对于通过字符串访问变量非常方便,即使它没有在窗口对象上定义。如果有一个名为MyClass的类,定义在一个名为MyClass.js的CommonJS模块中

// MyClass.js
var MyClass = function() {
    // I do stuff in here. Probably return an object
    return {
       foo: "bar"
    }
}

module.exports = MyClass;

然后你可以在另一个名为MyOtherFile.js的文件中做这个漂亮的巫术

// MyOtherFile.js

var myString = "MyClass";

var MyClass = require('./' + myString);
var obj = new MyClass();

console.log(obj.foo); // returns "bar"

CommonJS如此令人愉快的另一个原因。

JavaScript有一个eval函数,它计算字符串并将其作为代码执行:

eval(settings.functionName + '(' + t.parentNode.id + ')');

我更喜欢使用这样的方法:

window.callbackClass['newFunctionName'] = function(data) { console.log(data) };
...
window.callbackClass['newFunctionName'](data);

下面是一个更通用的方法来做同样的事情,同时支持作用域:

// Get function from string, with or without scopes (by Nicolas Gauthier)
window.getFunctionFromString = function(string)
{
    var scope = window;
    var scopeSplit = string.split('.');
    for (i = 0; i < scopeSplit.length - 1; i++)
    {
        scope = scope[scopeSplit[i]];

        if (scope == undefined) return;
    }

    return scope[scopeSplit[scopeSplit.length - 1]];
}

希望它能帮助一些人。