我有一个像这样的字符串:
settings.functionName + '(' + t.parentNode.id + ')';
我想翻译成这样的函数调用:
clickedOnItem(IdofParent);
当然,这必须使用JavaScript来完成。当我settings.functionName + '(' + t.parentNode.id + ')';对它发出警报时,似乎一切都正确了。我只需要调用它将转换为的函数即可。
传说:
settings.functionName = clickedOnItem t.parentNode.id = IdofParent
var fn = window[settings.functionName]; if(typeof fn === ‘function’) { fn(t.parentNode.id); }
编辑: 在这种情况下,settings.functionName将是"clickedOnItem"。这将在运行时转换varfn=window[settings.functionName];为var fn =window["clickedOnItem"],从而获得对的引用function clickedOnItem (nodeId) {}。一旦引用了变量内的函数,就可以通过“调用变量”来调用该函数,即fn(t.parentNode.id),等于clickedOnItem(t.parentNode.id)OP所需要的。
settings.functionName
"clickedOnItem"
varfn=window[settings.functionName];
var fn =window["clickedOnItem"]
function clickedOnItem (nodeId) {}
fn(t.parentNode.id)
clickedOnItem(t.parentNode.id)
更完整的例子:
/* 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); }