【问题标题】:accessing variable outside of $(document).ready() & jquery访问 $(document).ready() & jquery 之外的变量
【发布时间】:2011-08-13 02:57:33
【问题描述】:

所以我有一个包含在我的 html 中的 .js 文件

如果我把它放在我的 .js 文件中,

$(document).ready(function(){    
      var siteRoot = $('.site-root').val();
      alert(siteRoot);
});

代码会正确提醒该值,但如果我这样做:

var siteRoot = $('.site-root').val();
$(document).ready(function(){
      alert(siteRoot);
});

它会提醒 undefined

有没有办法让 $(document).ready() 中的东西访问它之外的变量,因为如果我将变量放在 $(document).ready() 中,它将无法从其他 js 文件中访问

【问题讨论】:

    标签: javascript jquery dom


    【解决方案1】:

    您可以将其设为全局:

    // this is the same as your example, 
    // just wanted to stress that it's a part of the window (global) object
    window.siteRoot = $('.site-root').val();
    $(document).ready(function(){
          alert(window.siteRoot);
    });
    

    或者更好的是,使用某种命名空间,像这样:

    var MyData = {};
    MyData.siteRoot = $('.site-root').val();
    
    $(document).ready(function(){
      alert(MyData.siteRoot);
    });
    

    【讨论】:

    • 你能给我举个命名空间方法的例子吗
    • 你去吧,这只是将东西放入对象的一种方式
    • 面部护理。是的,这是一种非常优雅的方式来持久化对象,而无需一长串全局声明。帮助很大。
    【解决方案2】:

    最好的方法是创建一个空的全局变量或创建一个命名空间来存储变量。然后在 document.ready 中将您的 $('.site-root').val() 添加到该变量中。

    var siteRoot = '';
    
    $(document).ready(function(){    
          siteRoot = $('.site-root').val();
          alert(siteRoot);
    });
    

    这样,您可以在知道 .site-root 存在之后设置 siteRoot 变量,并且它在整个应用程序中全局可用。

    【讨论】:

      【解决方案3】:

      变量 $(document).ready( 中可用,因为它是一个全局变量,但您可能会得到 undefined,因为在文档准备好之前,.siteRoot 没有可用的值。试试这个:

      var siteRoot = "blahblah";
      $(document).ready(function(){
            alert(siteRoot);
      });
      

      现在,如果您希望该变量 全局立即使用 在您的应用程序的其他部分中可以使用一个值,您将不得不重新设计您的解决方案,以便您的应用程序的其他部分也仅在 DOM 准备好时使用它。

      【讨论】:

        【解决方案4】:

        但您可以通过以下方式进行分享:

        $(document).ready(function(){
            window.siteroot = $('.site-root').val();
        });
        

        在整个应用程序中,您可以通过以下方式引用它:

        if (typeof(window.siteroot) !== "undefined") {
          //do this
        }
        

        你也可以延迟加载它:

        window.get_siteRoot = function() {
           if (typeof(window.siteroot) !== "undefined")
              return window.siteroot;
        
           var val = $('.site-root').val();
           window.siteroot = val;
           return window.siteroot;
        }
        

        HTH。

        【讨论】:

        • 最后3行可以是return window.siteroot = $('.site-root').val()
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-25
        • 2019-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多