$ .get()函数中的变量:无法再次访问该函数?

时间:2012-08-23 17:17:09

标签: javascript jquery

我还有另外一个javascript / jQuery的变量范围问题......

假设我声明了一个名为Container的对象。其中有一个名为myimage的变量,它将从某个xml文件中读取一个地址。

 Container = function()
 {
   var myimage;
 }

 Container.prototype.readXML = function()
 {
   $.get("assest/xml/images.xml",function(xml)
{
    //Read in URL path from XML file, and store them into memeber variables
    myimage = $(xml).find('background').text();
    //Apply background image into body, and apply css styple into it
    $("body").css('background-image','url(' + myimage + ')');
            //This alert will work
            alert(myimage);
});
            //This alert gives not defined variable
    alert(myimage);
  }

请查看两个警报部分。看来我在Container对象中定义的这个变量只能在readXML函数内部工作。但没有出去。我无法理解为什么会这样。

我确实使用了其他一些表示法,比如声明         this.myimage 并在执行$ .get函数之前通过将其名称更改为self来访问它         var self = this;

但它变得更糟。有时它甚至无法在get函数中达到。

你可以帮我这个吗?我的最终目标是该对象中的数组,并从XML中读取一堆数据,而不是将它们显示为HTML。如果无法访问我在Object中设置的变量,我就无法做到。

谢谢!

2 个答案:

答案 0 :(得分:1)

 Container = function()
 {
   var myimage;
 }

最有可能定义如下。更重要的是,$.get 异步所以你不能假设它按照它编写的顺序完成每行代码

 var Container = function()
 {
   this.myimage = '';
 }

Container.prototype.readXML = function(callback) {
    $.get("assest/xml/images.xml", function(xml) {
        //Read in URL path from XML file, and store them into memeber variables
        this.myimage = $(xml).find('background').text();
        //Apply background image into body, and apply css styple into it
        $("body").css('background-image', 'url(' + this.myimage + ')');
        //This alert will work
        callback(this.myimage);
    });
}​

var instance = new Container();
instance.readXML(function (copy) {
    alert(copy);
});​

答案 1 :(得分:0)

Javascript中未在全局范围内声明的所有变量都是声明它们的函数的本地变量。

由于函数是Javascript中的对象,因此可以为它们指定属性。所以,你可以做到

Container.myimage = $(xml).find('background').text();
//...
alert(Container.myimage);