所以我試圖提供一個簡單的網頁。在我的html中,我有一個表單,我想簡單地說任何搜索結果都找不到結果。如果我將javascript函數放入腳本標記到html文檔中,div將被填充。但是,每當我使用外部js文件它甚至不執行。控制檯不記錄任何內容,也不顯示警報。但是服務器正在提供這些文件,因爲如果我登錄請求URL,則會看到正在提供/button_click.js。有人能解釋爲什麼發生這種情況嗎這裏是我的參考代碼:外部javascript加載但不執行
的index.html
<!DOCTYPE html>
<html>
<head>
<style>
body{background: skyblue; font-family: verdana; color: #fff; padding: 30px;}
h1{font-size: 48px; text-transform: uppercase; letter-spacing: 2px; text-align:center;}
p{font-size: 16px; text-align:center;}
</style>
<script type="text/javascript" src="button_click.js">
// if uncommented and without the src tag this seems to do the job
// function buttonClick() {
// document.getElementById('result').innerHTML = "No results found";
// return false;
// }
</script>
</head>
<body>
<h1> Welcome to the home page</h1>
<form id="form" onsubmit="return buttonClick()">
<input type="text" name="search"> <br>
<input type="submit" name="submit"> <br>
</form>
<p id = "result">
</p>
</body>
</html>
button_click.js
function buttonClick() {
console.log('in here');
alert("in here");
document.getElementById('result').innerHTML = "No results found";
return false;
}
UPDATE
我的控制檯給了我一個意外的令牌lin的「<」錯誤e 1在我的js文件中。當我通過瀏覽器資源嘗試並檢查文件時,js文件顯然與我的index.html文件完全相同。它不包含javascript,並且包含index.html的內容。爲什麼是這樣?
我所有的文件都在同一目錄下,我已經檢查了所有的文件名作爲well.Here是我的服務器文件的參考內容:
server.js
const http = require('http');
const fs = require('fs');
const server = http.createServer(function(req, res) {
res.writeHeader(200, {"Content_Type": "text/html"});
var readStream = fs.createReadStream(__dirname + '/index.html', 'utf8');
readStream.pipe(res);
console.log(req.url);
console.log('served page');
});
server.listen(3000, '127.0.0.1');
console.log('Listening in port 3000');
如果存在src屬性,腳本標記之間的內容將被忽略,請參閱https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script – Teemu
您是否在瀏覽器控制檯中檢查過有什麼錯誤? –
在'document.onload();'中環繞button_click.js的內容並測試它是否有效。或在'