ClearInterval 没有停止
我正在尝试使用 setInterval 来检查当有人单击提交按钮时哈希值的变化。当点击提交按钮时,页面根本不会改变。仅改变哈希值。我想使用 setInterval 重复查找哈希值,直到它到达第 2 页(以防输入的表单值不正确)。一旦检测到page2,就会清除setInterval,但这部分不起作用。
var chkHash;
var hashval = window.location.hash;
var sb = document.getElementById("submitButton").onclick = function() {
startHash();
}
function checkHash() {
hv = window.location.hash;
if (hashval !== hv ) { hashval = hv; }
if(/page2/i.test(hv)) {
clearHash();
}
}
function startHash() {
chkHash = setInterval('checkHash()', 5000);
}
function clearHash() {
clearInterval(chkHash);
}
I'm trying to use setInterval to check for hash value change when a person clicks on a submit button. When the submit button is hit, the page will not change at all. Only the hash value is changed. I want to use the setInterval to repeatedly look for the hash value until it goes to page2 (in case the form values entered are incorrect). Once page2 is detected, it will clear the setInterval, but this part is not working.
var chkHash;
var hashval = window.location.hash;
var sb = document.getElementById("submitButton").onclick = function() {
startHash();
}
function checkHash() {
hv = window.location.hash;
if (hashval !== hv ) { hashval = hv; }
if(/page2/i.test(hv)) {
clearHash();
}
}
function startHash() {
chkHash = setInterval('checkHash()', 5000);
}
function clearHash() {
clearInterval(chkHash);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一些改进:
我还建议在函数
checkHash
内的hv = window.location.hash
之前添加var
,这样变量就不会泄漏到全球范围。Some improvements:
I also recommend to add
var
beforehv = window.location.hash
inside functioncheckHash
, so that the variable doesn't leak to the global scope.