使用body onload和document.write时忽略样式表 [英] Stylesheet ignored when using body onload and document.write

查看:79
本文介绍了使用body onload和document.write时忽略样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搞乱JavaScript实验以了解它并且已经遇到问题。这是我的HTML代码:

I am messing around with JavaScript experimenting to get a feel for it and have already hit a problem. Here is my html code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="testing.js"></script>
</head>
<body onload="writeLine()">
</body>
</html>

这是JavaScript testing.js:

Here is the JavaScript testing.js:

function writeLine()
{
    document.write("Hello World!")
}

这是样式表styles.css:

Here is the style sheet styles.css:

html, body {
    background-color: red;
}

这是一个非常简单的例子,但我可能选择了一个尴尬的例子,使用在身体标签中加载。所以上面的代码加载并运行函数,但样式表什么都不做,除非我删除头部的脚本标记。我已经尝试将脚本标记放在其他地方,但没有任何作用。我已经在线研究了如何正确链接到JavaScript文件,没有找到明确的解决方案,有没有人能指出我的错误?

So a very simple example, but I may have chose an awkward example, using on-load in a body tag. So the code above loads and runs the function, but the style sheet does nothing, unless I remove the script tags in the head. I have tried putting the script tags everywhere else, but nothing works. I have researched on-line how to properly link to JavaScript files, and have no found no clear solution, can anyone point out my error?

之前我使用过JavaScript,但是在我使用它之前我想从头开始明确理解

I have used JavaScript before, but I want a clear understanding from the beginning before I use it any longer

推荐答案

你的问题在于 document.write()在错误的时刻调用 * 。此方法在页面中的当前位置打印给定文本,以便在页面仍然加载时工作。因为你在整个页面加载时调用它,结果是意外的(未定义?)

Your problem is with the document.write() called in a wrong moment*. This method prints given text at current place in the page as was intended to work while the page still loads. Because you are calling it when the whole page was loaded, the results are unexpected (undefined?)

相反你应该操纵 dom 树的问题:

Instead you should manipulate the dom tree directly:

function writeLine() {
    var text = document.createTextNode("Hello World!");
    document.body.appendChild(text);
}

实际上在Opera浏览器中我看到红色背景几毫秒然后又回来了白色尝试注释 document.write() - 背景符合预期。此外,您应该在正文的末尾添加< script> 标记,但这不会解决您的问题。

Actually in Opera browser I see red background for few milliseconds and then it goes back to white. Try commenting out document.write() - the background is as expected. Moreover you should include <script> tag at the end of body, but this won't solve your problem.

*说实话,没有好时机调用 document.write(),避免它

* to be honest, there is no good moment for calling document.write(), avoid it

这篇关于使用body onload和document.write时忽略样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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