文档.Write不能工作,但是console.log可以

document.write doesnt work, but console.log does

本文关键字:console log 可以 但是 Write 不能 工作 文档      更新时间:2023-09-26

所以我创建了一个数组的事件由某用户在facebook上,我有所有的API的东西工作和一切,但我不能文档。写出来吧。

下面是我的代码:
for( var i = 0 ; i < response.length ; i++ ) 
{
    if (response[i]['eid'] > 0)
    {
        document.write([response[i]['name']] + '</br>' + response[i]['description']),
        console.log([response[i]['name']] + '</br>' + response[i]['description']);
    }
}

当我记录它时,它很好,但我实际上不能在页面上显示它。Alert()也可以。

有什么想法我可以吐出这些变量吗?

当你调用document。在页面加载后写入,它重写不包含返回数据的当前页面,或者对该数据进行循环迭代。因为你正在使用FB API,我猜这是在页面加载后运行。尝试使用客户端模板解决方案来呈现所有这些数据。这样,您就不必为您的数据创建一堆字符串连接。

如果页面的唯一目的是显示FB api调用的结果,那么只要您的页面设置为有效的HTML,并且您的所有javascript都包含在文档的头部部分,文档。写作应该是有效的。文档。Write通常只在页面加载之前使用,并且在正文中使用。一旦页面加载,整个文档的主体部分将被重写和替换。因此,如果您的任何脚本在正文中,它也将被替换。

在我看来,一个更好的选择是有一个div,并用结果填充div。

HTML:

<div id="results">
</div>
Javascript:

var results = "";
for( var i = 0 ; i < response.length ; i++ ) 
{
    if (response[i]['eid'] > 0)
    {
        results += response[i]['name'] + '</br>' + response[i]['description'];
        console.log(response[i]['name'] + '</br>' + response[i]['description']);
    }
}
document.getElementById("results").innerHTML = results;
编辑:我上面的解释是错误的,文档。如果在页面加载后使用Write,则重写整个文档。我上面的解决方案仍然是100%有效的。

以上公认的答案并非100%正确…下面的代码清楚地表明,即使文档被覆盖,至少已经在全局对象(窗口)中设置的函数和变量不会丢失,它们仍然运行。因此,如果您循环遍历已经设置的数据,它仍然会运行并显示结果,因此存在比javascript被覆盖更多的问题。

试一下:

<!DOCTYPE html>
<html>
<head>
<title>hi</title>
<script type="text/javascript">
    window.onload = function () {
        setTimeout(function () {
            for (i = 0; i < 10; i++)
                // this runs 3 seconds after the page loads, so after the first iteration
                // the entire document is erased and overwritten with 'hi',
                // however this loop continues to run, and write() continues to execute,
                // showing that the javascript still exists and operates normally.
                write();
        }, 3000);
    };
    // this variable will still exist after the page is overwritten
    window.someVar = "foo";
    // this function still exists and executes after the page is overwritten
    function write() {
        document.write("hi");
    }
</script>
</head>
<body>
<div>
    <b>hello</b>
</div>
</body>
</html>