我得到了一个字符串:

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

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

clickedOnItem(IdofParent);

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

传说:

settings.functionName = clickedOnItem

t.parentNode.id = IdofParent

当前回答

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

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

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

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

其他回答

window[settings.functionName](t.parentNode.id);

不需要eval()

因为我讨厌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);
}

如果设置。functionName已经是一个函数了,你可以这样做:

settings.functionName(t.parentNode.id);

否则,这也应该工作,如果设置。functionName只是函数名:

if (typeof window[settings.functionName] == "function") {
    window[settings.functionName](t.parentNode.id);
}
eval("javascript code");

它在处理JSON时被广泛使用。

我花了一段时间才弄清楚,因为传统的窗口['someFunctionName']()一开始并不适合我。我的函数名是作为AJAX响应从数据库中提取的。此外,由于某种原因,我的函数是在窗口的作用域之外声明的,所以为了解决这个问题,我不得不重写我调用的函数

function someFunctionName() {}

to

window.someFunctionName = function() {}

从那里我可以调用window['someFunctionName']()轻松。我希望这能帮助到一些人!