我有一个要求,我得到锚标签id并根据id确定要执行哪个函数..所以在代码下面有任何套件
function treeItemClickHandler(id)
{
a=findDisplay(id);
a();
}
答案 0 :(得分:2)
您可以将函数分配给变量,如下所示: 您还可以从函数返回函数指针 - 请参阅findDisplay(id)的return语句。
function treeItemClickHandler(id)
{
var a= findDisplay;
var other = a(id);
other();
}
function findDisplay(id)
{
return someOtherThing;
}
function someOtherThing()
{
}
答案 1 :(得分:1)
当然,JavaScript中的函数是第一类对象。例如,您可以创建一个映射(一个对象),该映射包含对您要调用的函数的引用:
var funcs = {
'id1': function(){...},
'id2': function(){...},
...
};
function treeItemClickHandler(id) {
if(id in funcs) {
funcs[id]();
}
}
由于函数被视为任何其他值,您也可以从其他函数返回它们:
function findDisplay(id) {
// whatever logic here
var func = function() {};
return func;
}
答案 2 :(得分:1)
函数是正常的javascript值,因此您可以传递它们,(重新)将它们分配给变量并将它们用作参数值或返回函数的值。只需使用它们;)到目前为止,您的代码是正确的。
答案 3 :(得分:1)
您可以通过多种方式在ID和函数之间进行映射。
其中一个更简单的方法是创建一个对象映射id到函数,并找到从该对象调用的函数(这本质上是一个更好看的switch
语句。)
示例:
function treeItemClickHandler(id)
{
var idMap = {
"some-id": findDisplay,
"another-id": doSomethingElse
};
if (!idMap.hasOwnProperty(id)) {
alert("Unknown id -- how to handle it?");
return;
}
// Call the corresponding function, passing the id
// This is necessary if multiple ids get handled by the same func
(idMap[id])(id);
}
function findDisplay(id)
{
// ...
}
function doSomethingElse(id)
{
// ...
}