我在页面上有一个链接,希望在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>
问题:超时不起作用,链接立即被替换。
只有在绑定到onLoad
事件的超时之后,才应该如何替换链接?
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');
}
}
评论您的侦听器并调用timeout_init((加载
// 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>