Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.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变量_Javascript - Fatal编程技术网

跨函数访问JavaScript变量

跨函数访问JavaScript变量,javascript,Javascript,我将一个变量设置为true,然后在两个不同的函数中进行检查,如果检查失败,则将其重新设置为false 在这里设置它 $(document).ready(function() { //Set enable_submit to true, then run checks to see if it should be reset to false var enable_submit = true; } 做其他检查。然后,看看这是否仍然是真的 function change_submi

我将一个变量设置为
true
,然后在两个不同的函数中进行检查,如果检查失败,则将其重新设置为false

在这里设置它

$(document).ready(function() {
    //Set enable_submit to true, then run checks to see if it should be reset to false
    var enable_submit = true;
}
做其他检查。然后,看看这是否仍然是真的

function change_submit_button_state() {
    if (enable_submit == true) {
        $("button[type=submit]").prop("disabled", false);
    } else {
        $("button[type=submit]").prop("disabled", true);
    }
}
问题是我得到了一个“ReferenceError:enable_submit未定义”,错误中引用的行是上面的
if(enable_submit==true){


有办法解决这个问题吗?

您应该将函数包装在
document.ready
方法中

$(document).ready(function() {
   //Set enable_submit to true, then run checks to see if it should be reset to false
   var enable_submit = true;
   function change_submit_button_state() {
     if (enable_submit == true) {
        $("button[type=submit]").prop("disabled", false);
     } else {
        $("button[type=submit]").prop("disabled", true);
     }
   }
}

在代码
中,enable\u submit
变量有一个局部作用域

您只需将函数包装在
document.ready
方法中即可

$(document).ready(function() {
   //Set enable_submit to true, then run checks to see if it should be reset to false
   var enable_submit = true;
   function change_submit_button_state() {
     if (enable_submit == true) {
        $("button[type=submit]").prop("disabled", false);
     } else {
        $("button[type=submit]").prop("disabled", true);
     }
   }
}

在您的代码
中,enable\u submit
变量有一个局部作用域

这是关闭的,但在我看来,最好的解决办法是将状态与
数据
存储在按钮上,然后访问它。它在任何地方都可用,并且可以避免globals@adeneo:你的想法有参考资料吗?不知道是什么“用按钮上的
数据存储状态”的意思是。这是关闭的,但在我看来,最好的答案是用按钮上的
数据存储状态,然后访问它。它在任何地方都可用,并且可以避免globals@adeneo:你的想法有参考资料吗?不知道是什么“用按钮上的
数据
存储状态”表示。