2013-07-08 54 views
0

我需要在ajax調用.loadUrl()後隱藏div(this.elmWheel)。如何在jQuery中追加另一個div後隱藏div?

使用此代碼我無法隱藏div。 我在這裏做錯了什麼? 我使用jQuery 1.4.2

var Viewer = function(url) { 
     var scope = this; 
     this.elm = '#viewer'; 
     this.elmWheel = '#loader-wheel'; 
     this.url = url; 
     this.init = function() { 
      this.loadWheelInit(); 
      this.loadUrl(); 
     }; 
     this.loadWheelInit = function() { 
      $('<div id="' + scope.elmWheel + '">Loading ...</div>').appendTo(this.elm); 
     }; 
     this.loadWheelHide = function() { 
      $(this.elmWheel).hide(); 
      console.log('hide'); 
     }; 
     this.loadUrl = function() { 
      // simulate loading 
      setTimeout(function() { 
       // fetch img from api 
       $.get(this.url, function(data) { 
        scope.loadWheelHide(); 
        console.log('show image'); 
        // add img to the dom 
        var img = $('<img id="img">'); 
        img.attr('src', this.url); 
        img.appendTo(scope.elm); 


       }); 
      }, 2000); 
     }; 
    }; 



     <div id="viewer" class=""> 

     </div> 

我創建一個實例與此代碼,圖像的Loadind輪被正確地追加,只是無法掩蓋它

var viewer = new Viewer('img/1.jpg'); 
    viewer.init(); 
+0

你如何創建一個'Viewer'實例?如何調用方法? – Olegas

+0

var viewer = new Viewer('img/1.jpg'); viewer.init(); – GibboK

回答

1

然後你正在創建一個裝載輪,它會得到一個錯誤的ID。

this.loadWheelInit = function() { 
    $('<div id="' + scope.elmWheel + '">Loading ...</div>').appendTo(this.elm); 
}; 

這導致

<div id="#loader-wheel">Loading...</div> 

loadWheelHide方法,你正在試圖通過選擇器#loader-wheel訪問負載輪,但也有不是這樣的ID。

您需要存儲的ID在elmWheel

this.elmWheel = 'loader-wheel' 

而且在前面加上一個井號,當你搜索

this.loadWheelHide = function() { 
    $('#' + this.elmWheel).hide(); 
    console.log('hide'); 
}; 
+0

非常感謝! – GibboK

+1

'#loader-wheel'是一個CSS選擇器,意思是「得到一個ID等於裝載輪的元素」。還有很多其他CSS選擇器,如'。'搜索具有特定CSS類的元素('$('。myClazz')'匹配'

'),或者只搜索標籤名稱以搜索指定的標籤('$('p')''匹配'

某些文本

')。那麼,你創建一個元素,你不需要傳遞一個選擇器,但是你可以搜索 - 你需要。 – Olegas