我需要一个脚本来检查某个函数是否在页面上,如果是,它会调用一个函数,如果没有,它会调用另一个函数。我还需要脚本以便在网页上自动输入。
这就是我的想法:
if(Examplefunction)
difffunction();
else
otherfunction();
答案 0 :(得分:0)
您需要小心检查可能尚未在JavaScript中定义的名称。引用未定义的名称将产生错误:
> if (Examplefunction) console.log('exists'); else console.log('???')
ReferenceError: Examplefunction is not defined
使用typeof
检查名称,但 是安全的,无论该名称是否已定义。因此,要检查变量是否已定义为真值,您应该使用:
if (typeof Examplefunction != 'undefined' && Examplefunction)
difffunction();
else
otherfuunction();
答案 1 :(得分:0)
它很简单:
if(funcNameHere){
funcNameHere(); // executes function
console.log('function exists');
}
else{
someOtherFunction(); // you can always execute another function
console.log("function doesn't exist");
}
想要制作能够完成所有工作的功能:
function funcSwitch(func1, func2){
var exc = func1 ? func1 : func2;
exc();
}
// check to see if `firstFunction` exists then call - or call `secondFunction`
fucSwitch(firstFunction, secondFunction);
当然,如果你没有传递一个函数变量,它就不会工作。函数名称基本上是在JavaScript中使用()
执行的变量。如果您习惯使用PHP,那么函数名称必须是String。它是JavaScript中的一个变量。
答案 2 :(得分:0)
if(typeof name === 'function') {
name();
}
else {
// do whatever
}
注意这是一个糟糕的设计。例如,你无法检查它所期望的参数数量。