如何在此jquery循环之外访问此变量? [英] How do I access this variable outside of this jquery loop?

查看:86
本文介绍了如何在此jquery循环之外访问此变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个遍历我的表单和

I have a simple jquery loop that goes through my form and

  1. 查看是否有空字段.
  2. 如果有任何内容为空,请使用空"类将其标记为
  3. 然后创建一个错误"变量

基本上:

// check all the inputs have a value...
$('input').each(function() {

    if($(this).val() == '') {

        $(this).addClass('empty');
        var error = 1;

    }   

});

这很有魅力.但是,随着代码的继续,我似乎无法访问该错误"变量……就好像它已锁定在每个循环中一样.在.each()循环之后紧接以下代码,即使我知道条件1和2都在工作,我也永远不会触发my_error_function().

This works a charm. However, as my code continues, I can't seem to access that 'error' variable... as though it is locked inside the each loop. With the following code being right after the .each() loop, I never get my_error_function() to fire, even though I know that criteria 1 and 2 are working.

if(error == 1) {

    my_error_function();

} else {

    my_non_error_function();

}

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

How do I access this variable so I can use its result elsewhere in the code?

推荐答案

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

Define your error variable outside of your function/loop

var error = 0;
$('input').each(function() {

    if($(this).val() == '') {

        $(this).addClass('empty');
        error = 1;

    }   

});

这篇关于如何在此jquery循环之外访问此变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆