問題描述
這個:
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";
這篇關于document.write() 覆蓋文檔?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!