本文介绍了全局变量如何在jquery / javascript中工作? (初学者级)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上想知道全局变量是如何在JavaScript / JQuery环境中工作的。我最熟悉一种叫做的语言,我被告知是基于Java的。我期望JavaScript和JQuery中的变量具有与处理中的变量相似的行为,但它们并不像我期望的那样工作,而且我不能在我的生活中围绕它进行思考。



我有一个非常简单的例子来说明我的困惑:

  

解决方案

如果语句只在DOM第一次准备就绪时运行一次。它没有连续运行。如果你希望它在点击处理程序中运行,那么你可以使用下面的代码:

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


I basically want to know how global variables work in a javascript/JQuery environment. I am most familiar with a language called processing which I've been told is java-based. 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.

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. 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".

If someone could explain why this happens, I will be very grateful!

解决方案

The if statement only runs once when the DOM is first ready. 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

这篇关于全局变量如何在jquery / javascript中工作? (初学者级)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:44