2015-01-07 138 views
1

我有一个小的C#代码背后如下15秒后刷新一个WebForm页面(form.aspx):自动刷新页面的倒计时

lblMessage.Text = "<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after 15 seconds)"; 
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setInterval(function(){location.href='/form.aspx';},15000);", true); 

眼下的页面将在15后刷新秒。我怎样才能让计时器每秒钟倒计时?即,15 => 14 => 13 => ... 1,那么刷新所以这将是更好地为用户,他们才知道是怎么回事,与网页...

+0

创建页面上的输入或元件,示出了计时器上的每个间隔向下计数。 – Mouser

+1

我认为这会更适合,更容易理解把它放在你的aspx而不是代码背后 – Kritner

回答

1
"<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after <span id='counter'>15</span> seconds)" 

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setTimeout(function(){location.href='/form.aspx';},15000); counter = 15; setInterval(function(){counter--; document.getElementById('counter').innerHTML = counter;},1000);", true); 

应该这样做。

如果在刷新消息编号周围添加了spanidcounter

然后我加了counter = 15;来初始化一个默认值15.而另一个setInterval给脚本块每秒触发一次。每次通过它会从counter中减去一个,并用新的计数器值更新span。用户现在应该看到页面倒计时。我还将第一个setInterval更改为setTimout,因为它在技术上是超时而不是每隔15秒发生的时间间隔。

+0

绝对天才!我正要将UpdatePanel,Timer,ScriptManager和所有类型的控件添加到aspx页面中,但这个工作非常简单。 –

+0

我可以再问你一个忙吗,现在我在aspx页面上使用updatepanel和timer显示一个时钟(小时:分钟+日期),它每隔30秒会引起服务器端回发,这不是一件好事,我怎么能使用javascript来做它,你的答案很简单,你可以将它添加到你的答案中。 –

+0

@RonaldinhoLearnCoding请开始一个新的问题或聊天,并为我提供一些代码。 – Mouser

3

在JavaScript中我会去这样的事情。

<div id='countdown'></div. 

var countDown = 15; 

function countdown() { 
    setInterval(function() { 
     if (countDown == 0) { 
      return; 
     } 
     countDown--; 
     document.getElementById('countdown').innerHTML = countDown; 
     return countDown; 
    }, 1000); 
} 

countdown(); 

小提琴:http://jsfiddle.net/chzzcosy/

+0

感谢这个非常干净的代码,也是一个工作演示,这完美的作品! –