这是我在aspx页面上的脚本,用于在页面加载时初始化计时器。
<script type="text/javascript">
function display() {
var hours = document.getElementById('<%=HidH.ClientID %>');
var minutes = document.getElementById('<%=HidM.ClientID %>');
var seconds = document.getElementById('<%=HidS.ClientID %>');
if (hours.value == 00 && minutes.value == 00 && seconds.value == 00) {
PageMethods.ReturnQuestionId(1);
alert("Time Given For this Test is Over");
var newwindow = window.location.replace("frmResultCheck.aspx");
if (window.focus) { newwindow.focus() }
return false;
}
if (minutes.value < 10) {
minutes.value = minutes.value;
}
if (seconds.value <= 00) {
if ((hours.value == 00) && (minutes.value == 00))
seconds.value = 00;
else {
seconds.value = 60;
minutes.value -= 01;
}
}
if (minutes.value <= 00) {
if ((hours.value < 00) && (seconds.value < 00)) {
hours.value = minutes.value = seconds.value = 00;
}
else {
if ((hours.value == 00) && (seconds.value == 00))
hours.value = seconds.value = 00;
if ((hours.value > 00) && (minutes.value < 00)) {
minutes.value = 59;
hours.value -= 01;
}
}
}
if ((minutes.value <= -01) || (hours.value <= -01)) {
if (hours.value <= -01) {
minutes.value = 00;
hours.value += 01;
}
else
minutes.value -= 01;
seconds.value = 00;
minutes.value += 01;
}
else
if (seconds.value > 00)
seconds.value -= 01;
if (hours.value.length < 2) {
hours.value = "0" + hours.value;
}
if (minutes.value.length < 2) {
minutes.value = "0" + minutes.value;
}
if (seconds.value.length < 2) {
seconds.value = "0" + seconds.value;
}
document.getElementById('counter').value = hours.value + ":" + minutes.value +
":" + seconds.value;
setTimeout("display()", 1000);
if (document.getElementById('btnSubmit').onclick == true)
document.getElementById('counter').value = "";
}
display();
</script>
这是我的aspx.cs页面:
protected void Page_Load(object sender, EventArgs e)
{
int factor;
if (factor >= 60)
{
int b = factor / 60;
factor = factor % 60;
string time = Convert.ToString(b + ":" + factor);
if (factor < 10)
{
timer = TimeSpan.ParseExact(time, @"h\:m", null);
}
else
{
timer = TimeSpan.ParseExact(time, @"h\:mm", null);
}
}
else if (factor > 9 && factor < 60)
{
timer = TimeSpan.ParseExact(factor.ToString(), "mm", null);
}
else
{
timer = TimeSpan.ParseExact("0" + factor.ToString(), "mm", null);
}
HidH.Value = Convert.ToString(timer.Hours);
HidM.Value = Convert.ToString(timer.Minutes);
HidS.Value = Convert.ToString(timer.Seconds);
}
每次我点击页面上的下一个按钮,计时器返回到我点击下一个按钮的同一时间。我希望我的计时器能够在回发时连续不断地继续。
答案 0 :(得分:0)
在C#Page_Load代码中,在初始化值之前检查它是否是回发。仅在首次加载时初始化(即!IsPostBack
)
像这样:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// Your initializing code here
}
}