我的JavaScript和HTML文件名爲contents.js和page.html中:調用JavaScript函數從HTML文件
function sayHello() {
alert("Hello World")
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="contents.js" ></script>
<script>
window.onload = sayHello();
</script>
</body>
</html>
當運行sayHello的功能不會被調用。在Firefox的控制檯則返回錯誤:
-SyntaxError:預計表達,得到了 '<' contents.js:1周
的ReferenceError:sayHello的是沒有定義
這兩個文件都保存在同一文件夾中。而我使用的是Node.js的快遞項目在Eclipse中創建服務器:
var http = require('http'),
fs = require('fs');
fs.readFile('./page.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8888);
});
爲什麼我無法從調用「sayHello的」功能在contents.js文件page.html文件?
'window.onload = sayHello();'將'sayHello'的返回值賦給'window.onload'。你回來了什麼? – Teemu
您忘了使用觸發事件。像'onload'或'onpageshow'。 –