2012-04-02 98 views
0

我遇到一個問題,我試圖使用jQuery將一些html加載到頁面上。'get'加載後的jQuery調用函數

內容本身加載正常,但我想要做的是使用jquery ui使該內容「可拖動」。

我遇到的問題是,當我調用該函數使內容可拖動時,它尚未加載,因此沒有任何內容可拖動。

我嘗試了一些成功,在函數調用之前添加了一個setTimeout,這讓它工作,但不是我想怎麼樣。 setTimeout不適用於緩慢的互聯網連接,或者當網站緩慢加載,因爲它太低。但是如果我把它設置的太高,那麼在內容可移動之前還有很長的等待時間。

我想知道在調用函數之前是否有方法檢測內容是否已經加載?

我的代碼:

$(".naviitem").click(function(){  //When icon is clicked 
    var i = $(this).attr('id');  //Get id of clicked icon 
    $.when(load(i)).then(makeDrag()); //Load page then call makeDrag (Doesn't function properly) 
    }); 


function load(i){ 

     $.get('wnd/' + i + '.htm', {}, function(data) { //This all works 
     var $response = $('<div />').html(data); 
     var $load = $response.find('#p' + i); 
     $('#page').append($load); 
     },'html'); 
    } 

function makeDrag(){ 
     //does something here 
    } 
+1

試着做''load'返回$ .get'。像:'function load(i){return $ .get(...}' – 2012-04-02 17:38:15

回答

1
$.when(load(i)).then(makeDrag()); 

這應該是:

$.when(load(i)).then(makeDrag); // Note the lack of() after makeDrag 

您需要的功能傳遞給.then,路過makeDrag()將結果傳遞Ø f函數,而不是函數本身。

另外,load應該return $.get$.when工作。

function load(i){ 
     return $.get('wnd/' + i + '.htm', {}, function(data) { //This all works 
     var $response = $('<div />').html(data); 
     var $load = $response.find('#p' + i); 
     $('#page').append($load); 
     },'html'); 
} 
+0

Thankyou,這工作很好:) – user1169601 2012-04-02 17:46:06

+0

@ user1169601:不客氣:-) – 2012-04-02 17:46:51

-1

可以使用$(文件)。就緒()..這會讓你知道,如果該頁面已被加載與否

1

我解決:

function load(i, afterLoad){ 
    $.get('wnd/' + i + '.htm', {}, function(data) { //This all works 
     var $response = $('<div />').html(data); 
     var $load = $response.find('#p' + i); 
     $('#page').append($load); 
     if(typeof afterLoad === 'function') //<-- see it 
     afterLoad(); 
    },'html'); 
    } 

而且使用它load(i, makeDrag)

+0

我會建議'if(typeof afterLoad = =='function')'在調用'afterLoad'之前。 – 2012-04-02 17:46:34

+0

@火箭我同意。修復它=) – gooogenot 2012-04-02 17:49:07