未定义onsubmit函数 [英] onsubmit function is not defined
问题描述
为什么说我没有定义函数?是因为我已将函数放置在文档就绪函数中吗? -也许我不得不提一下,如果我的陈述不正确,我想使用此功能阻止提交.
Why is it saying that I have not defined my function? Is it because I have placed my function inside a document ready function? - Maybe I have to mention that I want to use this function to prevent submitting if my statement is not true.
我的HTML表单标签:
my form tag in html:
<form class="text-left" method="post" action="" onsubmit="return myFunction();">
下面是脚本(此脚本在我的头部):
below is script(this script is in my head section) :
$( document ).ready(function() {
//the number generators and sum of the two numbers
var numberOne = Math.floor((Math.random() * 10) + 1);
var numberTwo = Math.floor((Math.random() * 10) + 1);
var sum = numberOne + numberTwo;
//write the math question to the div
document.getElementById("captchaOutput").innerHTML = numberOne+ " og " +numberTwo;
//alert(sum);
function myFunction(){
var humanInput = $('#captchaInput').val();
if(humanInput == sum){
$("#captcha_service_err").css("display", "inline")
$("#captchaInput").css("border-color", "red");
return false;
}
$("#captcha_service_err").css("display", "none")
$("#captchaInput").css("border-color", "");
return true;
}
});
推荐答案
是因为我已将函数放置在文档就绪函数中?
it because i have placed my function inside a document ready function?
是的.函数声明(如var
语句)的范围仅限于在其中声明的函数.
Yes. Function declarations are (like var
statements) scoped to the function they are declared within.
如果要使用myFunction
作为全局变量,则将其及其依赖的变量从in声明的匿名函数中移出.
If you want to use myFunction
as a global then move it, and the variables it depends on, out of the anonymous function you declare it with in.
或者,您可以显式创建一个引用它的全局变量:
Alternatively, you could explicitly create a global that references it:
window.myFunction = myFunction
但是,最好的解决方案是首先不要使用全局变量.
The best solution, however, is to not use a global in the first place.
删除onsubmit
属性,并改为使用JavaScript绑定事件处理程序.
Remove the onsubmit
attribute and bind your event handlers with JavaScript instead.
$('form').on('submit', myFunction);
确保捕获事件对象:
function myFunction(e){
然后,如果您不希望默认表单提交行为,则阻止它:
Then prevent the default form submission behaviour if you don't want it to submit:
$("#captchaInput").css("border-color", "red");
e.preventDefault();
这篇关于未定义onsubmit函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!