我遇到了一个问题,我试图使用jQuery将一些html加载到页面上。
内容本身加载正常,但我想做的是使用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
}发布于 2012-04-03 01:43:48
$.when(load(i)).then(makeDrag());这应该是:
$.when(load(i)).then(makeDrag); // Note the lack of () after makeDrag您需要将一个函数传递给.then,传递makeDrag()传递的是该函数的结果,而不是函数本身。
此外,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');
}发布于 2012-04-03 01:45:36
我的解决方案:
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)
发布于 2012-04-03 01:40:38
可以使用$(document).ready() ..这将让您知道页面是否已加载
https://stackoverflow.com/questions/9981008
复制相似问题