我用document.write()调用函数来添加内联内容(广告横幅):
<body>
Page content start<br>
<script>
function postContent(){
document.write('added content');
}
postContent();
</script>
<br>Page content end
</body>
在我得到的页面上:
Page content start
added content
Page content end
我想延迟添加此内容,但在 setTimeout() document.write() 内部覆盖所有内容。
<body>
Page content start<br>
<script>
function postContent(){
document.write('added content');
}
setTimeout(function () {
postContent();
}, 3000);
</script>
<br>Page content end
</body>
在 3 秒内的页面上,我得到了:
added content
如何延迟地使用 document.write() 调用函数并且不覆盖所有页面?
注意:我无权使用插入广告横幅的功能。
如果在加载文档后运行document.write
- 无论如何都会覆盖整个文档。因此,您应该选择一个特定的元素,并在其中添加内部 html 文本:
document.getElementById("container").innerHTML="added content";
您可以使用跨度并使用innerHTML
将行写入其中。
write()
函数第一次工作,因为它加载的时间与文档相同,因此在两者之间添加了行。
第二次重新加载文档时,删除所有 html。
<body>
Page content start<br>
<span id="pid"></span>
<script>
function postContent(){
document.getElementById("pid").innerHTML='added content';
}
setTimeout(function () {
postContent();
}, 3000);
</script>
<br>Page content end
</body>