我还有另一个 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 函数之前通过将 this 的名称更改为 self 来访问它 var self= this;
但它变得更糟。有时在 get 函数中甚至无法再访问它。
你能帮我解决这个问题吗?我的最终目标是该对象中的一个数组,并从 XML 中读取大量数据,而不是将它们显示为 HTML。如果无法达到我在 Object 中设置的变量,我就无法做到这一点。
谢谢!!