Mar*_*sen 1 javascript forms jquery onsubmit
为什么说我没有定义我的功能?是因为我已将我的功能放在文件就绪功能中吗? - 也许我必须提一下,如果我的陈述不正确,我想使用此函数来阻止提交.
我在html中的表单标签:
<form class="text-left" method="post" action="" onsubmit="return myFunction();">
Run Code Online (Sandbox Code Playgroud)
下面是脚本(这个脚本在我的脑子部分):
$( 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;
}
});
Run Code Online (Sandbox Code Playgroud)
Que*_*tin 10
因为我已将我的功能放在文件就绪功能中?
是.函数声明(如var
语句)作用于它们在其中声明的函数.
如果你想myFunction
用作全局,那么移动它,以及它所依赖的变量,你用它声明它的匿名函数.
或者,您可以显式创建引用它的全局:
window.myFunction = myFunction
Run Code Online (Sandbox Code Playgroud)
然而,最好的解决方案是首先不使用全局.
删除onsubmit
属性并使用JavaScript绑定事件处理程序.
$('form').on('submit', myFunction);
Run Code Online (Sandbox Code Playgroud)
确保捕获事件对象:
function myFunction(e){
Run Code Online (Sandbox Code Playgroud)
如果您不希望它提交,请阻止默认表单提交行为:
$("#captchaInput").css("border-color", "red");
e.preventDefault();
Run Code Online (Sandbox Code Playgroud)