控制来自第三方的 document.write 调用的范围
我正在编写一个依赖于外部 javascript 文件(我无法控制)的网页,该文件通过使用 document.write 返回数据。有没有办法动态调用该函数而不覆盖整个文档?这是我能想到的最简洁的代码:
<html>
<head>
<script type="text/javascript">
function horriblefunction () {
document.write("new text");
}
</script>
</head>
<body>
Starting Text...
<div id="pleasewriteinme"></div>
Other text...
<button onclick="horriblefunction();">Click</button>
</body>
</html>
这个想法是在不改变“horriblefunction()”(因为它是外部的)的情况下,新文本可以放置在 div 中而不是覆盖页面。这是可能的还是在创建页面时必须在 div 内部调用该函数?
谢谢你的帮助
I'm writing a webpage that relies on an external javascript file (that I have no control of), which returns data by using document.write's. Is there any way to dynamically call the function without it overwriting the whole document? Here's the most concise code I can think of:
<html>
<head>
<script type="text/javascript">
function horriblefunction () {
document.write("new text");
}
</script>
</head>
<body>
Starting Text...
<div id="pleasewriteinme"></div>
Other text...
<button onclick="horriblefunction();">Click</button>
</body>
</html>
The idea beginning that without altering "horriblefunction()" (as it's external) the new text could be placed in the div instead of overwriting the page. Is this possible or does the function have to be called inside the div as the page is created?
Thanks for you help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
页面完成渲染后使用
document.write
的唯一方法是暂时用您自己制作的函数替换该函数,将内容推送到 div 中。例如,只要外部 JS 已经加载并且您只是调用一个函数,这就会起作用。如果您需要加载 JS(例如,通过在 DOM 中插入一个新的
标签),请记住该操作是异步的,您需要观察 DOM 以了解它何时加载可以安全地恢复旧版本的
document.write
。The only way to use
document.write
after the page has finished rendering is to temporarily replace the function with one of your own making that will shove the content into a div. E.g.This will work as long as the external JS is already loaded and you're just calling a function. If you need to load the JS (say, by inserting a new
<script>
tag into the DOM) remember that that operation is asynchronous, and you'll need to watch the DOM to know when it's safe to restore the old version ofdocument.write
.尝试使用从 http://bezen.org/javascript/index.html 加载的动态脚本
bezen .domwrite.js - 捕获 document.write 和 writeln,以便在页面加载后安全加载外部脚本。
Try using dynamic script loading from http://bezen.org/javascript/index.html
bezen.domwrite.js - Captures document.write and writeln for the safe loading of external scripts after page load.