zoukankan      html  css  js  c++  java
  • js中return;return true return false 的区别

    return 定义:

    return 语句会 终止函数的执行 并 返回函数的值


     注意这两个: 1.终止函数的执行 2.返回函数的值

    返回函数的值这里就不过多叙述了,就是 return 变量

    先看下面的例子:

    <!DOCTYPE html>
    <html>
    <head>
        <title>return测试</title>
    </head>
    <body>
    <a href="#"></a>
    <a onclick="fun1()">111</a>
    <a onclick="fun2()">222</a>
    <a onclick="fun3()">333</a>
    <a onclick="fun4()">444</a>
    
    <script type="text/javascript">
        function fun1() {
            return ;
            console.log('111 这个不会执行')
        }
        function fun2() {
            return false
            console.log('222 这个不会执行')
        }
        function fun3() {
            return true
            console.log('333 这个不会执行')
        }
        function fun4() {
            console.log('444 这个会执行')
        }
    </script>
    </body>
    </html>

    通过上面的例子 可以看出  return ;    return false     return true   在函数内部都中断了函数的执行 

     接着看看 他们返回的结果是个啥 代码如下:

        function fun1() {
            return ;
        }
        function fun2() {
            return false
        }
        function fun3() {
            return true
        }
        console.log(fun1())
        // undefined
        console.log(fun2())
        // false
        console.log(fun3())
        // true

    返回的结果分别是  undefined  false  true  注:(undefine != false)

    有个知识点 : 表单提交的时候 如果函数返回 false  表单就不提交了 ,切记!

    首先看看能提交的情况,代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <title>return测试</title>
    </head>
    <body>
        <form method="post" onsubmit="return submitFunction()">
            <input type="text" name="nameId">
            <button type="submit" id="submit">提交</button> 
        </form>
    
    
    <script type="text/javascript">
        function submitFunction () {
            return ;
        }
    </script>
    </body>
    </html>

    效果如下: 右边出现了请求(注意:表单请求会刷新页面)

    阻止表单提交的代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <title>return测试</title>
    </head>
    <body>
        <form method="post" onsubmit="return submitFunction()">
            <input type="text" name="nameId">
            <button type="submit" id="submit">提交</button> 
        </form>
    
    
    <script type="text/javascript">
        function submitFunction () {
            return false;
        }
    </script>
    </body>
    </html>

    效果如下:右边没有出现请求,请求被阻止了


    总结如下:

    1. return ;  return false  return true 都会在函数内部阻止程序的执行。

    2. 只有 return false 会阻止表单的提交。

  • 相关阅读:
    WinForm 资源文件的使用
    php 常量
    netbean使用技巧
    netbeans 7安装xdebug调试php程序
    eclipse 开发技巧
    asp.net 获取客户机IP地址
    NameValueCollection详解
    Paramics插件编程进程间通讯
    Paramics API编程配置
    windows查询端口占用
  • 原文地址:https://www.cnblogs.com/yalong/p/9811176.html
Copyright © 2011-2022 走看看