Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在jquery循环之外访问此变量?_Javascript_Jquery - Fatal编程技术网

Javascript 如何在jquery循环之外访问此变量?

Javascript 如何在jquery循环之外访问此变量?,javascript,jquery,Javascript,Jquery,我有一个简单的jquery循环,它通过我的表单和 查看是否有空字段 如果有空的,用“empty”类标记它们,然后 然后创建一个“error”变量 基本上: // check all the inputs have a value... $('input').each(function() { if($(this).val() == '') { $(this).addClass('empty'); var error = 1; } })

我有一个简单的jquery循环,它通过我的表单和

  • 查看是否有空字段
  • 如果有空的,用“empty”类标记它们,然后
  • 然后创建一个“error”变量
  • 基本上:

    // check all the inputs have a value...
    $('input').each(function() {
    
        if($(this).val() == '') {
    
            $(this).addClass('empty');
            var error = 1;
    
        }   
    
    });
    
    这很有魅力。然而,随着代码的继续,我似乎无法访问“error”变量。。。好像它被锁定在每个循环中。由于下面的代码正好在.each()循环之后,我永远不会触发我的_error_function(),即使我知道条件1和2正在工作

    if(error == 1) {
    
        my_error_function();
    
    } else {
    
        my_non_error_function();
    
    }
    

    如何访问此变量,以便在代码中的其他位置使用其结果?

    在函数/循环之外定义错误变量

    var error = 0;
    $('input').each(function() {
    
        if($(this).val() == '') {
    
            $(this).addClass('empty');
            error = 1;
    
        }   
    
    });
    

    在范围外定义变量或将其分配给全局变量。名称间隔变量也起作用(例如foo.bar.error=1)

    $('input').each(function() {
       if($(this).val() == '') {
        $(this).addClass('empty');
        window.error = 1;
       }   
    });
    
    ...
    
    alert(error);