gpt4 book ai didi

javascript - 测试值是否为函数

转载 作者:IT王子 更新时间:2023-10-29 02:45:53 26 4
gpt4 key购买 nike

我需要测试表单的 onsubmit 的值是否是一个函数。格式通常为 onsubmit="return valid();"。有没有办法判断这是否是一个函数,以及它是否可调用?使用 typeof 只会返回它是一个字符串,这对我帮助不大。

编辑:当然,我理解“return valid();”是一个字符串。我已将其替换为“valid();”,甚至是“valid()”。我想知道其中任何一个是否是函数。

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

$("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() 不会触发现有的提交。

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;
}
} );

关于如何更好地做到这一点的建议?

最佳答案

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

无论您是分配 onsubmit HTML 属性还是在 JavaScript 中分配它,以上内容都应该有效:

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

关于javascript - 测试值是否为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/798340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com