【问题标题】:Getting Timeout to work让超时工作
【发布时间】:2018-07-19 11:04:09
【问题描述】:
我在页面上有一个链接,我希望在onLoad 之后定义超时后,此链接将被另一个链接替换。我有以下示例代码:
window.addEventListener('DOMContentLoaded', changeLinks, false);
function timeout_init() {
setTimeout('changeLinks()', 30000);
}
window.onload = changeLinks;
var _linksChanged = false;
function changeLinks() {
if(_linksChanged) return;
_linksChanged = true;
var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href = aEl.href.replace('https://google.com','https://yahoo.com');
}
}
<a href="https://google.com" target="_blank">link</a>
问题:超时不起作用,链接被立即替换。
只有在超时绑定到onLoadevent 后才替换链接?
【问题讨论】:
标签:
javascript
timeout
settimeout
onload
onload-event
【解决方案1】:
window.onload = function() {
var _linksChanged = false;
setTimeout(changeLinks, 30000);
}
function changeLinks() {
if(_linksChanged) return;
_linksChanged = true;
var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href =
aEl.href.replace('https://google.com','https://yahoo.com');
}
}
【解决方案2】:
评论你的听众
并调用 timeout_init() onload
// window.addEventListener('DOMContentLoaded', changeLinks, false);
function timeout_init() {
setTimeout('changeLinks()', 30000);
}
window.onload = timeout_init();
var _linksChanged = false;
function changeLinks() {
if(_linksChanged) return;
_linksChanged = true;
var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href = aEl.href.replace('https://google.com','https://yahoo.com');
}
}
<a href="https://google.com" target="_blank">link</a>