我对Javascript很新。我正在尝试实现一个控制页面是否刷新的按钮。但是,它不起作用(单击按钮会触发一些操作,如警报等,但不会更改标签按钮,并且不会停止刷新页面。)
你能告诉我哪里出错了吗?这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Message log</title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body onload="JavaScript:timedRefresh(5000);">
<button id="bRefresh" onclick="refreshMode()">Stop refreshing</button>
some content...
</body>
</html>
<script type="text/JavaScript">
<!--
var refresh = 1;
function timedRefresh(timeoutPeriod) {
if(refresh == 1) {
setTimeout("location.reload(true);",timeoutPeriod);
}
}
function refreshMode() {
if(refresh == 1) {
var refresh = 2;
document.getElementById("bRefresh").value="Start refreshing";
} else {
var refresh = 1;
document.getElementById("bRefresh").value="Stop refreshing";
}
};
// -->
</script>
答案 0 :(得分:1)
您的代码应如下所示,
var refresh = 1;
var timedInterval= null;
function timedRefresh(timeoutPeriod) {
if(refresh == 1) {
timedInterval = setInterval(function() { location.reload(true); },timeoutPeriod);
}
}
function refreshMode() {
if(refresh === 1) {
refresh = 2;
clearInterval(timedInterval);
document.getElementById("bRefresh").innerHTML="Start refreshing";
} else {
refresh = 1;
timedRefresh(5000);
document.getElementById("bRefresh").innerHTML="Stop refreshing";
}
//document.getElementById("bRefresh").innerHTML="Start refreshing";
};
对重复的任务使用setInterval而不是setTimeout
您声明刷新变量三次,因此您的按钮值不会更改。
innerHTML而不是value应该用于更改Buttons文本。
如上所述停止使用clearInterval。
答案 1 :(得分:0)
<button id="bRefresh">Stop refreshing</button>
var button = document.getElementById("bRefresh");
var refresh = 1;
var timeoutPeriod = 5000;
var id;
function timedRefresh() {
if (refresh == 1) {
window.location.reload(true);
}
}
function refreshMode() {
if (refresh == 1) {
clearInterval(id);
refresh = 2;
button.textContent = "Start refreshing";
} else {
id = setInterval(timedRefresh, timeoutPeriod);
refresh = 1;
button.textContent = "Stop refreshing";
}
};
button.addEventListener("click", refreshMode, false);
id = setInterval(timedRefresh, timeoutPeriod);
on jsfiddle
答案 2 :(得分:0)
将innerHTML用于supporting IE < 9
var button = document.getElementById("bRefresh");
var refresh = 1;
function refreshMode() {
if (refresh == 1) {
refresh = 2;
button.innerHTML = "Start refreshing";
} else {
vrefresh = 1;
button.innerHTML = "Stop refreshing";
}
};
button.addEventListener("click", refreshMode, false);
答案 3 :(得分:0)
在正文加载时,prepareRefresh()
函数检查值refresh
(设置为1)并开始刷新页面超时。
您应该启动刷新,在刷新之前,您必须检查refresh
值。因为在第一种情况下,location.reload
不关心refresh
的修改。检查超时结束时的refresh
值
<script type="text/JavaScript">
<!--
var refresh = 1;
function timedRefresh(timeoutPeriod) {
if(refresh == 1) {
setTimeout("refreshPage();",timeoutPeriod);
}
}
function refreshPage ()
{
if(refresh == 1) {
setTimeout("location.reload(true);", 0);
}
}
function refreshMode() {
if(refresh == 1) {
refresh = 2;
document.getElementById("bRefresh").innerHTML="Start refreshing";
} else {
refresh = 1;
document.getElementById("bRefresh").innerHTML="Stop refreshing";
}
};
// -->
</script>