document.write() 覆盖文档?
这个:
function myFunction()
{
document.write("sup");
}
在 html 中调用如下:
called in html like:
<div id="myDiv">
<script>myFunction();</script>
</div>t
将字符串 sup
添加到 myDiv
div 元素.这正是我想要的.但是,这个:
adds a string sup
to the myDiv
div element. Which is what I want, exactly. However, this:
function loadFile(uri)
{
var r = new XMLHttpRequest();
document.write("trying to open: " + uri);
r.open('GET', uri, true);
r.send(null);
r.onreadystatechange = function()
{
if (r.readyState == 4)
{
myFunction();
}
}
}
function myFunction()
{
document.write("sup");
}
这样称呼:
<div id="myDiv">
<script>loadFile("filename.txt");</script>
</div>
似乎覆盖了我的整个 html 文件.IE.当我在 Firefox 中运行它时,它只显示字符串 sup
(这是页面的全部内容),但页面似乎仍在加载(FF 的加载图标仍然存在动画,显然是无限的).
seems to be overwriting my whole html file. I.e. when I run it in Firefox it shows me only the string sup
(that's the whole content of the page) but the page seems to be still loading (the loading icon of FF is still there animating, apparently infinitely).
首先,这将仅在本地离线使用,作为一种快速便捷的数据呈现方式(使用 html+js 和 Web 浏览器而不是纯文本文件).我想要的是加载一个本地文本文件,然后将它的一些内容作为 html 页面的一部分.与我的第一个示例相同,但首先加载文本文件.
First of all, this is going to be used only locally, offline, as a fast and handy way of presenting data (using html+js and web browser instead of plain text file). What I want is to load a local text file and then put some of its content as a part of the html page. The same as in my first example but with loading the text file first.
推荐答案
问题是当你在文档加载后运行 document.write 时,它会覆盖整个文档.如果在此之前运行,它不会覆盖它.
The issue is that when you run document.write after the document has loaded, it overwrites the entire document. If it is run before that, it does not overwrite it.
您要做的是设置特定元素的innerHtml,例如:
What you want to do is set the innerHtml of a specific element, something like:
document.getElementById("myDiv").innerHTML="Sup";
相关文章