访问jquery.ready()之外的变量

Accessing a variable outside of jquery.ready()

本文关键字:变量 jquery ready 访问      更新时间:2023-09-26

这变得非常令人沮丧,所以我希望有人能帮忙。我不是一个优秀的JavaScript或JQuery开发人员(更多的是后端人员(,但我到处寻找解决方案,似乎没有任何帮助。这是我问题的简化版本。。。

<script language="JavaScript" type="text/javascript">
fooey = 'baaa';
jQuery(document).ready(function($) {
fooey = 'New value';     
});
alert("value: " + fooey);  // I need this to be 'New value'
</script>

如何更改JQuery块内部的fooey变量,然后从JQuery块外部访问这个新值。因此,我希望弹出的警报显示"新值",而不是"baaa"。

您的代码可以工作,但它按以下顺序运行:

  1. fooey="baaa";

  2. 设置jQuery(文档(.ready

  3. alert("value:"+fooey(;

  4. 运行jQuery(文档(.ready

之所以会发生这种情况,是因为JavaScript在document准备就绪之前运行(并且jQuery事件触发(。因此,如果在document准备就绪之前使用fooey,则应将其设置为'New value'。如果您需要在DOM就绪时使用它,请在$(document).ready函数结束时使用它。

解释

加载网页后,会运行页面中的JavaScript。这将通过代码(设置和警告fooey的值(,设置任何事件,如.onclickwindow.onresize$(document).ready(),这些事件将在以后特定事件发生时调用。对于$(document).ready(),它发生在DOM(文档对象模型(准备好进行操作时

从jQuery API ready((:

直到完全接收到诸如图像之类的所有资产,才触发该事件。

在ready函数中定义警报,原因是在document.ready函数之前执行警报。

<script language="JavaScript" type="text/javascript">
    fooey = 'baaa';
    jQuery(document).ready(function($) {
        fooey = 'New value';     
        alert("value: " + fooey);  // I need this to be 'New value'     
    });
</script>

javascript:

var foo;
        $(function() {   
           // this is your jquery.ready() function. I have write it in another way
           foo = 'val1'
           alert(foo);
        });
      function fun(){
        foo = 'val2';
        alert(foo);
      }
      function fun2(){
        alert(foo);
      }

HTML代码:

   <input type="button" id="b1" value="b1" onclick="fun()" >
   <input type="button" id="b2" value="b2" onclick="fun2()">

这里foo变成a global variablepage loading上的foo的值是val1

如果单击按钮b1,则其值将变为val2。您可以通过单击按钮b2来检查此值。

ready子句的全部目的是等待文档完全就绪后再执行任何操作。通过在该事件之外添加代码,它将(可能(在就绪事件之前加载。

<script language="JavaScript" type="text/javascript">
// executed when browser interprets this line
fooey = 'baaa';  // (1st to be executed)
jQuery(document).ready(function($) {
// executed after few seconds , when DOM is ready.   (3rd one to be executed)
 fooey = 'New value';     
});

// executed when browser interprets this line (2nd one to be executed)
alert("value: " + fooey);  
</script>

最后一个fooey值是New value,但当您提醒它时不是

您可以像这样等待DOM准备就绪。

<script language="JavaScript" type="text/javascript">
fooey = 'baaa';   
jQuery(document).ready(function($) {
 fooey = 'New value';     
});
var interval = setInterval(function () {
   if ( jQuery.isReady ) {
      clearInterval(interval);
      alert("value: " + fooey);
   }   
},10)
</script>