testing值是否是一个函数

我需要testing一个表单的onsubmit值是否是一个函数。 格式通常是onsubmit="return valid();" 。 有没有办法告诉这是一个函数,如果它是可调用的? 使用typeof只是返回它是一个string,这并没有多大帮助。

编辑 :当然,我明白“返回有效();” 是一个string。 我已经replacereplace成“valid();”,甚至“valid()”。 我想知道这些是否是一个function。

编辑 :这是一些代码,这可能有助于解释我的问题:

 $("a.button").parents("form").submit(function() { var submit_function = $("a.button").parents("form").attr("onsubmit"); if ( submit_function && typeof( submit_function.replace(/return /,"") ) == 'function' ) { return eval(submit_function.replace(/return /,"")); } else { alert("onSubmit is not a function.\n\nIs the script included?"); return false; } } ); 

编辑2 :这是新的代码。 看来,我仍然必须使用eval,因为调用form.submit()不会触发现有的onsubmits。

 var formObj = $("a.button").parents("form"); formObj.submit(function() { if ( formObj[0].onsubmit && typeof( formObj.onsubmit ) == 'function' ) { return eval(formObj.attr("onsubmit").replace(/return /,"")); } else { alert("onSubmit is not a function.\n\nIs the script included?"); return false; } } ); 

可能如何做得更好的build议?

我用锚链接replace提交button。 由于调用form.submit()不会激活onsubmit的,我find它,并自己eval()。 但是我想在eval()之前检查函数是否存在。 – gms8994

 <script type="text/javascript"> function onsubmitHandler() { alert('running onsubmit handler'); return true; } function testOnsubmitAndSubmit(f) { if (typeof f.onsubmit === 'function') { // onsubmit is executable, test the return value if (f.onsubmit()) { // onsubmit returns true, submit the form f.submit(); } } } </script> <form name="theForm" onsubmit="return onsubmitHandler();"> <a href="#" onclick=" testOnsubmitAndSubmit(document.forms['theForm']); return false; "></a> </form> 

编辑:在函数testOnsubmitAndSubmit中缺less参数f

无论您是分配onsubmit HTML属性还是使用JavaScript分配,上面都应该可以工作:

 document.forms['theForm'].onsubmit = onsubmitHandler; 

尝试

 if (this.onsubmit instanceof Function) { // do stuff; } 

您可以简单地使用typeof运算符以及三元运算符:

 onsubmit="return typeof valid =='function' ? valid() : true;" 

如果它是一个函数,我们称之为返回值,否则返回true

编辑:

我不太清楚你真正想做什么,但我会试着解释可能发生的事情。

当你在你的html中声明你的onsubmit代码时,它会变成一个函数,因此它可以从JavaScript“世界”中调用。 这意味着这两种方法是等价的:

 HTML: <form onsubmit="return valid();" /> JavaScript: myForm.onsubmit = function() { return valid(); }; 

这两个将是两个function,都将被调用。 您可以使用typeof运算符来testing其中的任何一个,它们应该具有相同的结果: "function"

现在,如果您通过JavaScript为“onsubmit”属性指定一个string,它将保持一个string,因此不可调用。 注意,如果你对它应用typeof运算符,你会得到"string"而不是"function"

我希望这可以澄清一些事情。 然后,如果你想知道这个属性(或者任何标识符)是否是一个函数并且是可调用的,那么操作符的types就应该这样做。 虽然我不确定它是否可以在多个框架中正常工作。

干杯

你使用的是什么浏览器?

 alert(typeof document.getElementById('myform').onsubmit); 

这给了我在IE7和FireFox中的“ function ”。

确保你在实际函数上调用了typeof,而不是string文字:

 function x() { console.log("hi"); } typeof "x"; // returns "string" typeof x; // returns "function" 

你可以尝试修改这个技巧来满足你的需求:

  function isFunction() { var functionName = window.prompt('Function name: '); var isDefined = eval('(typeof ' + functionName + '==\'function\');'); if (isDefined) eval(functionName + '();'); else alert('Function ' + functionName + ' does not exist'); } function anotherFunction() { alert('message from another function.'); } 

当form.onsubmit定义为HTML元素的属性时,它始终是一个函数。 它是附加到HTML元素的某种匿名函数,它具有绑定到该FORM元素的这个指针,并且还有一个名为event的参数,它将包含关于submit事件的数据。

在这种情况下,我不明白你是如何得到一个string作为一种操作的结果。 你应该给更多的细节,更好的一些代码。

编辑 (作为对第二次编辑的回应):

我相信附加到HTML属性的处理程序将会执行而不pipe上面的代码。 此外,你可以尝试阻止它,但是,看起来FF 3,IE 8,Chrome 2和Opera 9正在执行HTML属性处理程序在第一个地方,然后附加的一个(我没有testing与jQuery虽然,但与addEventListener和attachEvent)。 所以…你想要完成什么?

顺便说一句,你的代码不工作,因为你的正则expression式会提取string“valid();”,这绝对不是一个函数。

如果它是一个string,你可以假设/希望它始终是forms

 return SomeFunction(arguments); 

parsing函数名称,然后查看该函数是否使用定义

 if (window[functionName]) { // do stuff } 

那么"return valid();" 一个string,所以这是正确的。

如果你想检查是否有附加的function,你可以试试这个:

 formId.onsubmit = function (){ /* */ } if(typeof formId.onsubmit == "function"){ alert("it's a function!"); } 

我认为混淆的根源是节点属性和相应属性之间的区别。

您正在使用:

 $("a.button").parents("form").attr("onsubmit") 

你直接读取onsubmit 属性的值(它必须是一个string)。 相反,您应该访问节点的onsubmit 属性

 $("a.button").parents("form").prop("onsubmit") 

这是一个快速testing:

 <form id="form1" action="foo1.htm" onsubmit="return valid()"></form> <script> window.onload = function () { var form1 = document.getElementById("form1"); function log(s) { document.write("<div>" + s + "</div>"); } function info(v) { return "(" + typeof v + ") " + v; } log("form1 onsubmit property: " + info(form1.onsubmit)); log("form1 onsubmit attribute: " + info(form1.getAttribute("onsubmit"))); }; </script> 

这产生:

 form1 onsubmit属性:(函数)函数onsubmit(event){return valid();  }
 form1 onsubmit属性:(string)return valid()
  if ( window.onsubmit ) { // } else { alert("Function does not exist."); } 

您可以在JavaScript博客(如Chris West's)上始终使用typeOf函数之一。 对typeOf()函数使用如下定义将会工作:

 function typeOf(o){return {}.toString.call(o).slice(8,-1)} 

这个函数(在全局命名空间中声明的)可以像这样使用:

 alert("onsubmit is a " + typeOf(elem.onsubmit)); 

如果是function,则返回“function”。 如果是string,则返回“String”。 其他可能的值显示在这里 。

 // This should be a function, because in certain JavaScript engines (V8, for // example, try block kills many optimizations). function isFunction(func) { // For some reason, function constructor doesn't accept anonymous functions. // Also, this check finds callable objects that aren't function (such as, // regular expressions in old WebKit versions), as according to EcmaScript // specification, any callable object should have typeof set to function. if (typeof func === 'function') return true // If the function isn't a string, it's probably good idea to return false, // as eval cannot process values that aren't strings. if (typeof func !== 'string') return false // So, the value is a string. Try creating a function, in order to detect // syntax error. try { // Create a function with string func, in order to detect whatever it's // an actual function. Unlike examples with eval, it should be actually // safe to use with any string (provided you don't call returned value). Function(func) return true } catch (e) { // While usually only SyntaxError could be thrown (unless somebody // modified definition of something used in this function, like // SyntaxError or Function, it's better to prepare for unexpected. if (!(e instanceof SyntaxError)) { throw e } return false } } 

使用一个基于string的variables作为例子,并使用instanceof Function您注册函数..分配variables…检查variables是函数的名称…做前处理…分配function,以新的variables..然后调用该函数。

 function callMe(){ alert('You rang?'); } var value = 'callMe'; if (window[value] instanceof Function) { // do pre-process stuff // FYI the function has not actually been called yet console.log('callable function'); //now call function var fn = window[value]; fn(); } 

像这样的一个简单的检查会让你知道它是否存在/定义:

 if (this.onsubmit) { // do stuff; }