简体   繁体   English

全局变量如何在jquery / javascript中工作? (初学者级)

[英]How do global variables work in jquery/javascript? (beginner-level)

I basically want to know how global variables work in a javascript/JQuery environment. 我基本上想知道全局变量在javascript / JQuery环境中如何工作。 I am most familiar with a language called processing which I've been told is java-based. 我最熟悉的一种称为处理的语言是基于Java的。 I expected variables in javascript and JQuery to behave like the ones in processing, but they do NOT work as I expect and I cannot for the life of me wrap my head around it. 我期望javascript和JQuery中的变量的行为像处理中的那样,但是它们无法按我预期的那样工作,而且我一生都无法解决。

I have a very simple example made up to illustrate my confusion: 我有一个非常简单的示例来说明我的困惑:

 var what="";

 $(document).ready(function(){
      $("p").click(function () {
           what="p";
           });
      if(what=="p"){
            alert(what);
           }//end if
 });//end doc ready

In processing, this would work because the 'what' variable is global and as it is changed by clicking on a paragraph, the if statement should be continuously checking to see if 'what'=='p', and trigger the alert. 在处理过程中,这是可行的,因为'what'变量是全局变量,并且通过单击段落进行更改,因此if语句应不断检查以查看'what'=='p'并触发警报。 But that is not what happens-- 'what' only seems to be updated WITHIN the click function, even though it is a global variable, so when it comes to the if statement, 'what' still equals "" instead of "p". 但这不是发生的事情-'what'似乎只是在click函数内更新,即使它是全局变量,因此在if语句中,'what'仍等于“”而不是“ p” 。

If someone could explain why this happens, I will be very grateful! 如果有人能解释为什么会这样,我将非常感谢!

The if statement only runs once when the DOM is first ready. if语句仅在DOM准备就绪时仅运行一次。 It is not running continuously. 它没有连续运行。 If you want it to run during the click handler, then you would use this code: 如果希望它在点击处理程序中运行,则可以使用以下代码:

 var what="";

 $(document).ready(function(){
    $("p").click(function () {
       what="p";
       if(what=="p"){
           alert(what);
       }//end if
    });
});//end doc ready

the if statement should be continuously checking to see if 'what'=='p', and trigger the alert. if语句应不断检查以查看'what'=='p',并触发警报。

Why? 为什么? None of your code produces that functionality. 您的代码均未产生该功能。 If you want that to happen, you can use setInterval() : 如果您希望这种情况发生,可以使用setInterval()

setInterval(function() {
    if(what=="p") { 
        alert("what");
    }
}, 500); // executes function every 500 milliseconds

But that is not what happens-- 'what' only seems to be updated WITHIN the click function, even though it is a global variable 但这不是发生的事情-'what'似乎只是在click函数内更新,即使它是全局变量

No, your what variable is being updated globally. 不,你what变量正在全球范围内更新。 You just don't notice because you made false assumptions about the if functionality (it's only being called once). 您只是没有注意到,因为您对if功能(它只被调用了一次)做出了错误的假设。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM