document.write()覆盖文档? [英] document.write() overwriting the document?

查看:121
本文介绍了document.write()覆盖文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  function myFunction()
{
document.write(sup) ;

在html中调用:

 < div id =myDiv> 
< script> myFunction();< / script>

t

添加一个字符串 sup myDiv div元素。这正是我想要的,完全是。然而,这个:

pre $ function loadFile(uri)
{
var r = new XMLHttpRequest();
document.write(试图打开:+ uri);
r.open('GET',uri,true);
r.send(null);
r.onreadystatechange = function()
{
if(r.readyState == 4)
{
myFunction();



$ b函数myFunction()
{
document.write(sup);
}

这样调用:

 < div id =myDiv> 
< script> loadFile(filename.txt);< / script>
< / div>

似乎会覆盖整个html文件。即当我在Firefox中运行它时,它只显示字符串 sup (这是页面的全部内容),但页面似乎仍在加载(FF的加载图标是仍然有动画效果,显然是无限的)。

首先,这将仅用于本地,离线,作为呈现数据的一种快速且方便的方式(使用html + JS和网页浏览器,而不是编排文本文件)。我想要的是加载一个本地文本文件,然后把它的一些内容作为html页面的一部分。与我的第一个示例相同,但首先加载文本文件。 解决方案

问题是,当您运行document.write文档加载完成后,它会覆盖整个文档。如果它在此之前运行,它不会覆盖它。



您要做的是设置特定元素的innerHtml,如下所示:

  document.getElementById(myDiv)。innerHTML =Sup; 


This:

function myFunction()
{
    document.write("sup");
}

called in html like:

<div id="myDiv">
    <script>myFunction();</script>
</div>t

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");
}

called like this:

<div id="myDiv">
    <script>loadFile("filename.txt");</script>
</div>

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).

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 plaing 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.

解决方案

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.

What you want to do is set the innerHtml of a specific element, something like:

document.getElementById("myDiv").innerHTML="Sup";

这篇关于document.write()覆盖文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆