测试值是否为函数 [英] Testing if value is a function
问题描述
我需要测试表单的 onsubmit
的值是否为函数。格式通常为 onsubmit =return valid();
。有没有办法判断这是否是一个函数,如果它是可调用的?使用typeof只返回它是一个字符串,这对我没什么帮助。
I need to test whether the value of a form's onsubmit
is a function. The format is typically onsubmit="return valid();"
. Is there a way to tell if this is a function, and if it's callable? Using typeof just returns that it's a string, which doesn't help me much.
编辑:当然,我明白返回有效();是一个字符串。我已经将
替换为valid();,甚至是valid()。我想知道其中任何一个是否是函数。
EDIT: Of course, I understand that "return valid();" is a string. I've replace
d it down to "valid();", and even "valid()". I want to know if either of those is a function.
编辑:这里有一些代码,可能有助于解释我的问题:
EDIT: Here's some code, which may help explain my problem:
$("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。
EDIT 2: Here's the new code. It seems that I still have to use an eval, because calling form.submit() doesn't fire existing 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;
}
} );
关于如何做得更好的建议?
Suggestions on possibly how to do this better?
推荐答案
我正在用
锚链接替换提交按钮。因为调用
form.submit()不会激活
onsubmit's,我找到了它,并且我自己发现了
eval()。但我想
检查函数是否存在于
之前只是eval()那里有什么。 - gms8994
I'm replacing a submit button with an anchor link. Since calling form.submit() does not activate onsubmit's, I'm finding it, and eval()ing it myself. But I'd like to check if the function exists before just eval()ing what's there. – 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中缺少参数f
EDIT : missing parameter f in function testOnsubmitAndSubmit
无论您是分配 onsubmit
HTML属性还是用JavaScript分配它,上述内容都应该有效:
The above should work regardless of whether you assign the onsubmit
HTML attribute or assign it in JavaScript:
document.forms['theForm'].onsubmit = onsubmitHandler;
这篇关于测试值是否为函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!