[英]Beginner javascript
I'm new to JavaScript and web design in general, and I don't understand why this doesn't work. 我是JavaScript和Web设计的新手,但我不明白为什么这不起作用。
There are two problems. 有两个问题。
1) The title of my page doesn't work, and instead in the browser title bar what is displayed is " myHtml.html
". 1)我页面的标题不起作用,而是在浏览器标题栏中显示的是“
myHtml.html
”。 The title only works if I take the declaration of the script
out. 仅当我删除
script
声明时,标题才有效。
2) I want the text generated by JavaScript to be blue, is there a way to do that? 2)我希望JavaScript生成的文本为蓝色,有没有办法做到这一点?
HTML: HTML:
<!DOCTYPE html>
<html>
<head class = "Header">
<title>JavaScript Test</title>
<meta charset = "UTF-8">
<link rel = "stylesheet" type = "text/css" href = "myCSS.css" >
<script type= text/javascript src= myJavaScript.js></script>
</head>
<body class = "Body" onload = "testJavaScript()">
<p>
<noscript>
Your javascript is disabled
</noscript>
</p>
</body>
</html>
JavaScript: JavaScript的:
function testJavaScript(){
var message = "You Have Javascript!!";
document.writeln(message);
}
CSS: CSS:
@charset "UTF-8";
head.Header{
font-family:sans-serif;
color:green;
}
body.Body{
font-family:sans-serif;
color:blue;
}
When you use document.writeln
after the onload
event fires (like you have it in your example), the whole DOM will be deleted and therefore there is no HTML/CSS left to give you either a title or a blue text. 当在
onload
事件触发后使用document.writeln
时(就像您在示例中一样),整个DOM将被删除,因此没有HTML / CSS留下标题或蓝色文本。
To test what you are trying to do, do this: 要测试您要执行的操作,请执行以下操作:
...
<body class="Body">
<p>
<noscript>
Your javascript is disabled
</noscript>
<script>
testJavaScript();
</script>
</p>
...
However, I would recommend you don't use document.writeln
at all (unless there is a good reason) and use DOM manipulation methods to include your text (eg innerHTML
). 但是,我建议您不要使用
document.writeln
(除非有充分的理由),而不要使用DOM操作方法来包含您的文本(例如innerHTML
)。 @Shylo's answer is also an approach to take. @Shylo的答案也是采取的方法。
<!DOCTYPE html>
<html>
<head class="Header">
<title>JavaScript Test</title>
<meta charset="UTF-8">
<style type="text/css">
.Body {
font-family: sans-serif;
color: blue;
}
</style>
<script type="text/javascript">
window.onload = function() {
message = document.createElement('P');
message.className = "Body";
message.innerHTML = "You Have Javascript!!";
document.body.appendChild(message);
}
</script>
</head>
<body>
<p>
<noscript>
Your javascript is disabled
</noscript>
</p>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.