简体   繁体   English

为什么我的变量在Javascript / Jquery中不全局可用?

[英]Why isn't my variable available globally in Javascript / Jquery?

I'm trying to declare a global variable called GlobalVarTest , which is defined in a function within my function LikeTermsCombiner2() . 我试图声明一个名为GlobalVarTest的全局变量,该变量在我的函数LikeTermsCombiner2()中的函数中定义。 In the code below, .ReplaceThis gets replaced successfully, as it appears within the same function in which the variable is defined, but .ReplaceThis2 does not get replaced outside of the function. 在下面的代码中, .ReplaceThis被成功替换,因为它出现在定义变量的同一函数中,但是.ReplaceThis2不在函数外部被替换。

I noted in the code where I've also tried to declare GlobalVarTest . 我在代码中指出,我也曾尝试声明GlobalVarTest

My actual code is rather long, but I whittled it down to the bare bones so that it's clear where all of the functions are. 我的实际代码很长,但是我将其精简了一下,以使所有功能都清晰可见。 (In other words, some functions appear not to do anything in this code, but they serve a purpose in the actual code.) (换句话说,某些函数在此代码中似乎没有执行任何操作,但是在实际代码中它们是有目的的。)

var GlobalVarTest;

function LikeTermsCombiner2() {


   //var GlobalVarTest; Tried putting this here

  $(function() { 

   //var GlobalVarTest; Also tried putting this here

    $(function() { 

        GlobalVarTest = "5";  
        $(".ReplaceThis").html(GlobalVarTest);      

    });  

   $(".ReplaceThis2").html(GlobalVarTest);      


    });

}


$('.Expression').each(function() {

  console.log(LikeTermsCombiner2());

 });

http://jsfiddle.net/2x7049bs/162/ http://jsfiddle.net/2x7049bs/162/

Solution

You can move your embdedded function into a separate function and return a variable, assigning this to something within the first function. 您可以将嵌入的函数移到一个单独的函数中,然后返回一个变量,将其分配给第一个函数中的某个对象。 This does not need to be used, but will ensure the first function waits for the second to complete before continuing. 不需要使用此功能,但可以确保第一个功能在第二个功能完成之前先等待。 As demonstrated below, this means that the global value is no longer undefined. 如下所示,这意味着全局值不再是未定义的。

Please see the demo below for a working example. 请参阅下面的演示以获取工作示例。


Explaination

$(function() { ... }

The code above is short hand for making a function run on window load, the issue you is that although you are assigning them in various locations, that does not mean the will be completed in that order. 上面的代码是使函数在窗口加载时运行的简捷方式,问题是,尽管您在各个位置分配了它们,但这并不意味着将按该顺序完成。

Moving the $(".ReplaceThis2").html(GlobalVarTest); 移动$(".ReplaceThis2").html(GlobalVarTest); to after the closing tag of function LikeTermsCombiner2() { ... } will still not necessarily work. function LikeTermsCombiner2() { ... }的结束标记之后仍然不一定有效。 That function effectively adds a function to the run list after page load, but does not wait for it to be run (this function then adds a second to the run list, but again does not wait for it to be completed). 该功能在页面加载后有效地将功能添加到运行列表中,但不等待其运行(此功能随后在运行列表中添加了第二个功能,但再次不等待其完成)。

Adding a function to the run list is a much quicker action than actually processing that entire element of code so the 'parent' function races ahead without variables being defined. 将函数添加到运行列表比实际处理整个代码元素要快得多,因此“父”函数可以在不定义变量的情况下快速运行。


Demo 演示

 var GlobalVarTest; function LikeTermsCombiner2() { //var GlobalVarTest; $(function() { // Move current code into a separate function. // Call the separate function and assign to variable to ensure function waits for result waitForComplete = setGlobalFn(); $(".ReplaceThis2").html(GlobalVarTest); }); return "LikeTermsCombiner2 return value"; } // Bring the code that sets GlobalVarTest into a different function function setGlobalFn() { // Your code... // Set GlobalVarTest GlobalVarTest = "5"; // Replace as needed $(".ReplaceThis").html(GlobalVarTest); // Return a value (does not need to be used) return true; } $('.Expression').each(function() { console.log(LikeTermsCombiner2()); }); 
 .root { border-top: thin black solid; } .root>sup { vertical-align: baseline; position: relative; top: -0.4em; font-size: 70%; } .Index { vertical-align: baseline; position: relative; top: -0.4em; font-size: 70%; } .index { vertical-align: baseline; position: relative; top: -0.4em; font-size: 70%; } span[class*='variable'] <span class="Parentheses FirstSet">(<span class="TermWrapper"><span class="Coefficient">1</span></span>) </span><span class="Parentheses SecondSet">( 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="Expression"></span> <br> This should say five: <span class="ReplaceThis"></span> <br> This should also say five: <span class="ReplaceThis2"></span> 

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

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