我在表单提交按钮的单击事件上调用函数时出现引用错误

时间:2015-03-19 15:20:33

标签: javascript jquery html forms

我正在尝试将表单提交给服务器,但必须首先通过函数进行验证。但是,即使我声明了函数,我仍然会获得引用错误。此外,当我单击按钮时,即使我没有将click属性添加到按钮,它也会一直提交。

<html id="website" class="no-js" lang="">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style>
        body {
            padding-top: 50px;
            padding-bottom: 20px;
        }
    </style>
    <link rel="stylesheet" href="css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="css/main.css">

    <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
    <script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

    <script src="js/vendor/bootstrap.min.js"></script>
    <script src="js/plugins.js"></script>        
    <script src="js/main.js"></script>

    <script>
        jQuery(document).ready(function($){

            var onlineStatus = true;
            var formObjects = null;

            //Local Storage or Send to Server
            function save(){

                if(onlineStatus == false){

                    formObjects = $('#form').serializeObject();
                    alert("saving to local: " + formObjects);
                    alert(formObjects.length);

                } else{
                    alert("submitting!!");
                    $("#form").submit();
                }
            }

        });             
    </script>
</head>
<body>

<form id="form" role="form" method="post" action="https://www.webserver.com/echo.php">
<div id="form1" class="container">
    <h1>Personal Information</h1>
       <div class="form-group">
          <label for="name">Name</label>
          <input id="name" name="name" type="text" required
             placeholder="Enter Name">
       </div>
       <div class="form-group">
          <label for="email">E-mail:</label>
          <input id="email" name="email" type="email" required
             placeholder="E-mail">
       </div>

   <button id="submitButton" class="btn btn-default" onclick="save();return false;" >Submit</button>

</div> 
</form>  

</body>

1 个答案:

答案 0 :(得分:1)

范围就是一切! save函数在.ready方法中定义,因此只能在那里访问。您必须在该范围之外声明此函数:

var onlineStatus = true;
var formObjects = null;

//Local Storage or Send to Server
function save(){
//stuff here
}
jQuery(document).ready(function($){