需要什么明确的“返回”?使用 Javascript 在表单中使用 onsubmit 时的关键字?

发布于 2024-12-07 11:22:09 字数 1187 浏览 0 评论 0原文

我有C/C++编程背景,在通过JS上的@3C网页随意学习Javascript时,我发现了这段代码——

<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>

嗯,我不知道我是否错过了他们之前的任何课程;我对该行中使用的“return”感到困惑 -

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">

我的问题 - 由于调用函数“validateForm()”时上述行中的“onsubmit”无论如何都会是寻找返回值 true/false,这个显式 return 关键字的意义是什么?我看到删除 return 关键字并运行上面的代码(如 - onsubmit = "validateForm();" )可以工作,但即使输入中存在错误,表单最终也会在之后提交显示警告消息。

您能否解释一下在这种情况下“return”关键字的使用?

另外,考虑到我的 c/c++ 背景,我发现 Javascript 的编写方式存在很多偏差。我一个人在这里吗? :)

谢谢!

I have a C/C++ programming background, and while casually learning Javascript through the @3C webpages on JS, I found this piece of code -

<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>

Well, I do not know if I have missed out any of their previous lessons; am confused over the "return" used in the line -

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">

My question - Since the "onsubmit" in the above line on calling the function "validateForm()" will anyways be looking for a return value of true/false, what is the significance of this explicit return keyword? I see that on deleting the return keyword, and running the above code (as - onsubmit = "validateForm();" ) works, but even if an error in input is there the form ultimately gets submitted after displaying the warning message.

Could you please throw some light on the use of this "return" keyword in this scenario?

Also, I find that there is a lot of deviation in the way Javascript is written, considering my background in c/c++.. am i alone here..? :)

thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

泛泛之交 2024-12-14 11:22:10

好吧,似乎出现了一些误导性的答案,所以我会尝试提供一个解释。符号 被翻译为如下内容:(

element.onsubmit = function (event) {
    with (document) {
        with (this) {
            handler_body
        }
    }
};

我们将忽略与 with 相关的内容,它在这里并不重要。)现在,考虑 validateForm() 函数返回 false。如果您使用 onsubmit="return validateForm()",随后显然会变成 onsubmit="return false",您的处理程序将变为

element.onsubmit = function () {
    return false;
};

submit 事件被触发(就像浏览器内部调用 element.onsubmit()),element.onsubmit() 返回 false,因此默认值被抑制。

但是,如果您只使用 onsubmit="validateForm();",事件处理程序将类似于

element.onsubmit = function () {
    false;
};

在本例中,false 只是一个语句。 element.onsubmit() 不会返回任何内容,并且从事件处理程序返回 undefined 不足以阻止默认行为。

@Simeon 告诉“不需要 HTML 中的返回。”,但他实际上还在代码中使用了return false

OK, it seems there appear some misleading answers, so I'll try to provide an explanation. The notation <element onsubmit="handler_body"> is translated to something like:

element.onsubmit = function (event) {
    with (document) {
        with (this) {
            handler_body
        }
    }
};

(We'll ignore the with-related stuff, it's not important here.) Now, consider the validateForm() function returns false. If you use onsubmit="return validateForm()", what subsequently turns obviously into onsubmit="return false", your handler will become

element.onsubmit = function () {
    return false;
};

When the submit event is triggered (it's like the browser internally calls element.onsubmit()), element.onsubmit() returns false and thus the default value is suppressed.

However, if you'd just use onsubmit="validateForm();", the event handler would look like

element.onsubmit = function () {
    false;
};

In this case, false is just a statement. element.onsubmit() doesn't return anything, and returning undefined from the event handler isn't enough to prevent the default behaviour.

@Simeon told that "The return in HTML is not needed.", but he actually also uses return false in his code.

匿名。 2024-12-14 11:22:10

HTML 中的 return 是不需要的。根据记录,以编程方式附加事件既更美观又更强大:

<html>
    <head>
    <script type="text/javascript">

        var myForm = document.getElementById("myForm");

        myForm.onsubmit = function() {
            var x = myForm["email"].value;
            var atpos = x.indexOf("@");
            var dotpos = x.lastIndexOf(".");

            if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
                alert("Not a valid e-mail address");
                return false;
            }
        };
    </script>
    </head>
    <body>
        <form id="myForm" action="demo_form.asp" method="post">
            <label>
                Email:
                <input type="text" name="email">
            </label>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

The return in HTML is not needed. For the record, to attach the event programmatically is both more beautiful and powerful:

<html>
    <head>
    <script type="text/javascript">

        var myForm = document.getElementById("myForm");

        myForm.onsubmit = function() {
            var x = myForm["email"].value;
            var atpos = x.indexOf("@");
            var dotpos = x.lastIndexOf(".");

            if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
                alert("Not a valid e-mail address");
                return false;
            }
        };
    </script>
    </head>
    <body>
        <form id="myForm" action="demo_form.asp" method="post">
            <label>
                Email:
                <input type="text" name="email">
            </label>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>
冷情妓 2024-12-14 11:22:10

相信大家已经差不多回答了这个问题,只是方式不同而已。谢谢你们。

我碰巧在网上读到一篇精彩的文章,它使用一个与我发布的问题非常相似的示例,很好地解释了实际发生的事情,主要是在幕后。

觉得这对将来可能遇到此问题的任何人都会有用。

文章链接 - http://www.quirksmode.org/js/events_early.html
阅读该页面的“防止默认”部分。

——阿伦·奈尔

I believe everyone has nearly answered the question, but then in different ways. Thanks guys.

I happened to read an excellent article online, which beautifully explains what is actually happening, mostly behind the scenes, using an example that closely resembles the question that I had posted.

Felt this would turn useful for anyone who might face this issue in the future.

Link to the article- http://www.quirksmode.org/js/events_early.html
Read the "Prevent Default" section of the page.

--arun nair

只涨不跌 2024-12-14 11:22:09

如果函数返回 false,则事件被取消。

onsubmit="return validateForm();"

有点相当于

onsubmit="if(!validateForm()) stop the event"

当然,还有其他(更干净的)方法来停止事件 dom-propagation :

function stopEvent(event){
    if(event.preventDefault)
         event.preventDefault();
    if(event.stopPropagation)
         event.stopPropagation();
    event.cancelBubble = true;
}

然后将其用于事件处理程序:

onsubmit = function(e){
    if(!validateForm())
        stopEvent(e);
}

well if the function returns false, then the event is canceled.

onsubmit="return validateForm();"

is somewhat equivalent to

onsubmit="if(!validateForm()) stop the event"

Of course, that there are other(cleaner) methods of stopping the event dom-propagation :

function stopEvent(event){
    if(event.preventDefault)
         event.preventDefault();
    if(event.stopPropagation)
         event.stopPropagation();
    event.cancelBubble = true;
}

and then use it into an event-handler :

onsubmit = function(e){
    if(!validateForm())
        stopEvent(e);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文