函数jQuery之间传递的全局变量

时间:2012-07-04 02:45:17

标签: jquery function variables global-variables

我在if ... else语句中设置变量。但是,当我尝试在另一个函数中调用变量时,我得到的错误是未定义变量。如何设置全局变量?

function username_check(){  
username = $('#username').val();
if(username == "" || username.length < 7 || username.indexOf(' ') > -1){
    usernameFilled = 0;
else{
    usernameFilled = 1;
}   
}

function email_check(){ 
email = $('#email').val();
if(email == "" || email.indexOf(' ') > -1) {
    emailFilled = 0;
}else{
    emailFilled = 1;
}
}

function password_length(){ 
password = $('#password').val();
if(password == "" || password.indexOf(' ') > -1) {
    passwordFilled = 0;
}else{
    passwordFilled = 1;
}
}

function password_check(){  
  password2 = $('#password2').val();
  password = $('#password').val();
  if(password2.length > 7 && password2 == password) {
    password2Filled = 1; /**setting the variable**/
  }else{
    password2Filled = 0;
  }
}

function upload(){
if (usernameFilled == 0 || emailFilled == 0 || passwordFilled == 0 || password2Filled == 0) {
    alert('All fields are required');
}else{
    /**upload to database**/
}

3 个答案:

答案 0 :(得分:1)

而不是设置全局变量只返回password2Filled并将其保存在函数之外。然后你可以将它传递给下一个函数。

function password_check(){  
   password2 = $('#password2').val();
   password = $('#password').val();
   if(password2.length > 7 && password2 == password) {
       password2Filled = 1; /**setting the variable**/
   }else{
       password2Filled = 0;
   }
   return password2Filled;
}

function upload(password2Filled)
{
    if (password2Filled == 0) { /**calling the variable**/
        alert('All fields are required');
    }else{
        /**upload to database**/
    }
}

....

var passwordsOk = password_check();
upload(passwordOk);

尝试并避免使用全局变量,它们会使程序混乱,并且难以查看代码流并创建可重用的代码。

答案 1 :(得分:1)

你可能是以错误的顺序调用函数,或者做错其他的事情,因为它对我来说效果很好,稍微编辑代码来测试它:

function password_check(){  
  var password2 = $('#password2').val(), 
      password = $('#password').val();
  password2Filled = (password2.length > 7 && password2 == password) ? 1:0;
}

function upload(){
    console.log(password2Filled); //prints 0 or 1 just fine ???
}

$("#btn").on('click', function() {
    password_check();
    upload();
});

FIDDLE

答案 2 :(得分:0)

通过在所有函数范围之外定义全局变量,可以在JavaScript中创建全局变量。像这样:

<script type="text/javascript">
var globalVariable;


function blah()
{
    globalVariable = "something";
}

function anotherFunction()
{
    alert(globalVariable);
}
</script>

ECMAScript / JavaScript documentation表示应在任何执行上下文之外创建“全局对象”。