我得到了一个字符串:
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或这个方法。