我只是学习JavaScript,出于某种原因,这个简单的例子(来自Chapter One的示例1)示例在我的任何浏览器中都不起作用(Jon Duckett的JavaScript和Jquery书):FireFox,IE和Chrome。我确保JavaScript已打开。我还在我的index.html文件中放了noscript标签,以确保我有JavaScript。我的jsFiddle工作得很好,但在我的浏览器中没什么。这是我的jsFiddle以及我在Atom编辑器中的所有内容。我的链接是正确的,因为我复制了完整路径,然后将其粘贴到src中。然后我删除了所有的C:\ users .......直到我进入包含所有文件的文件夹,最终得到了jsFiddle中的内容。
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="etf-8" />
<title>Greeting JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
<script src="scripts/greeting.js"></script>
</head>
<body>
<noscript>Your Browser Does Not Support JavaScript. Please Enable It.</noscript>
<section>
<div id="header">
<h1>Constructive & Co.</h1>
</div>
<h3 id="greeting"></h3>
<p>For all orders and inquiries please call <em>555-3344</em></p>
</section>
</body>
</html>
的javascript:
var today = new Date();
var hourNow = today.getHours();
var greeting;
if (hourNow > 18) {
greeting = 'Good evening!';
} else if (hourNow > 12) {
greeting = 'Good afternoon!';
} else if (hourNow > 0) {
greeting = 'Good morning!';
} else {
greeting = 'Welcome!';
}
document.getElementById("greeting").innerHTML = greeting;
的CSS:
@import url(http://fonts.googleapis.com/css?family=Open+Sans:800italic);
body {
font-family: "Courier New", Courier, monospace;
/*background: url("../images/constructive-backdrop.jpg") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;*/
background: #a18957;
margin: 0px;
padding: 0px;
text-align: center;
}
section {
margin-top: 20px;
margin-left: 20px;
height: 500px;
width: 400px;
background: #eee;
border: 1px solid #292929;
}
#header {
height: 200px;
margin: 10px;
background: rgba(227, 192, 186, 0.78);
}
h1 {
margin: 0px;
position: relative;
top: 45%;
}
h3 {
height: 100px;
margin: 10px;
background: red;
}
p {
margin: 10px;
height: 100px;
}
谢谢
答案 0 :(得分:0)
您想在html的末尾添加script
标记。执行时,元素greeting
不存在。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Greeting JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<noscript>Your Browser Does Not Support JavaScript. Please Enable It.</noscript>
<section>
<div id="header">
<h1>Constructive & Co.</h1>
</div>
<h3 id="greeting"></h3>
<p>For all orders and inquiries please call <em>555-3344</em></p>
</section>
<script src="scripts/greeting.js"></script>
</body>
</html>
或者你将它留在头部并将脚本包装成
addEventListener("readystatechange", function () {
if (document.readyState === "interactive") {
var today = new Date();
var hourNow = today.getHours();
var greeting;
if (hourNow > 18) {
greeting = 'Good evening!';
} else if (hourNow > 12) {
greeting = 'Good afternoon!';
} else if (hourNow > 0) {
greeting = 'Good morning!';
} else {
greeting = 'Welcome!';
}
document.getElementById("greeting").innerHTML = greeting;
}
}, false);
使用document.getElementById
代替document.write
!