2012-04-02 96 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