未定义onsubmit函数

编程入门 行业动态 更新时间:2024-10-22 07:28:09
本文介绍了未定义onsubmit函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么说我没有定义函数?是因为我已将函数放置在文档就绪函数中吗? -也许我不得不提一下,如果我的陈述不正确,我想使用此功能阻止提交.

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函数

本文发布于:2023-11-28 06:56:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641374.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   未定义   onsubmit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!