2012-03-22 85 views
0

我在jQuery的这个函数,从POST页获取数据,然后将反应到一个div:jQuery的延迟后的数据为DIV

$("#go").click(function(){ 
    $.post("get.php", {p: 'abc'}, function(data){ 
    $('#result').html(data); 
    }); 
}); 

这工作,但反正是有延迟数据进入#result标签约3秒?

最后,我想在标签说:

“加载”,“中..”和“载入中...”一秒钟每个,然后显示数据。

回答

1

试试这个:

$("#go").click(function(){ 
    // Show loader here 
    $.post("get.php", {p: 'abc'}, function(data){ 
     setTimeout(function() { 
      // Hide loader here 
      $('#result').html(data); 
     }, 3000); 
    }); 
}); 
7

这是您应该使用的语法。

var delayCounter = 3; 
var delayTimer = ''; 
delayTimer = setInterval(function(){ 
    if (delayCounter > 0){ 
    $('#result').html('Loading...'); 
    }else{ 
    $('#result').html(data); 
    clearInterval(delayTimer); 
    } 
    delayCounter--; 
},1000); 

这里发生了什么?

  • 我们使用delayCounter变量来计算我们延迟动作的次数。它的起始值是3 - 所以我们将被“延迟”3次。
  • delayTimer变量是计时器本身,将计数每个延迟。
  • 我们使用setInterval函数,这正是我们想要做的 - 设置执行我们的代码之间的时间间隔。
  • clearInterval是相当自我解释 - 这结束并清除计时器。
  • 对于每次迭代,我们减少delayCounter变量,以便我们可以跟踪已经通过了多少间隔。
  • 我们使用毫秒来定义延迟 - 在这里我使用了1000秒,这是1秒(1000秒)。

还有一个另外你可能想实现的是,而不是简单地把“加载”文本在你的元素,让它多一点通过附加文本,使其动态。
什么可能是有趣的是追加省略号单词“加载”到得到这样的效果:

​​

首先设置初始值“加载”然后追加每一个点 -

$('#result').html($('#result').html()+'.'); 
// Loading 
// Loading. 
// Loading.. 
// Loading... 

这就是说你也可以只取GIF动画,并使用该:P

+2

Geeees - 这是采取** **永远载入! – Lix 2012-03-22 12:37:03

2

尝试:


setTimeout(function() { 
    $('#result').html(data); 
}, 3000); 
2

编辑:更新,增加了加载功能。

$("#go").click(function(){ 
    $.post("get.php", {p: 'abc'}, function(data){ 
    window.intervalTimer = setInterval(function(data) { 
     if (!window.timeoutCount) 
      window.timeoutCount = 0; 

      if (++window.timeoutCount > 3) { 
       $('#result').html(data); 
       clearInterval(window.intervalTimer); 
      } 
      else 
        $('#result').html("Loading..") 
    }, 1000); 
    }); 
}); 
2

要延迟在JavaScript中功能的执行使用setTimeout方法。作品有点像:

var doLater = setTimeout(function(){ 
alert('I like to wait 5 seconds'); 
},5000); //delay is stated in ms 

在你的情况,将在最后:

$("#go").click(function(){ 
    $.post("get.php", {p: 'abc'}, function(data){ 
    var wait = setTimeout(function(){$('#result').html(data);},3000); 
    }); 
}); 
+0

-1您的'setInterval'永远不会被清除。在解释'setInterval'时,明确需要详细说明'clearInterval'函数。 – Lix 2012-03-22 12:39:31

+0

@lix:哦,我非常抱歉,并不意味着写了我真正写的东西 – m90 2012-03-22 12:49:28

+0

我也有时在他们之间感到困惑!删除-1,并upvoted :) – Lix 2012-03-22 12:51:10

1
$("#go").click(function(){ 
    $.post("get.php", {p: 'abc'}, function(data) { 
    $('go').html('Loading.'); 
    setTimeout("function() { 
     $('go').html('Loading..'); 
    }",1000); 
    setTimeout("function() { 
     $('go').html('Loading...'); 
    }",1000); 
    $('#result').html(data); 
    } 
} 
+0

+1有点太冗长,我喜欢:P但它应该工作! – Lix 2012-03-22 12:40:21