[英]file doesn't work when javascript moves to external file
I'm trying out socket.io and downloaded its GitHub project . 我正在尝试socket.io并下载了它的GitHub 项目 。
It worked fine, but when I tried to move the inline js code to an external file, it stopped working. 它工作正常,但是当我尝试将内联js代码移动到外部文件时,它停止工作。 Why is that so?
为什么会这样? What did I do wrong?
我做错了什么?
In its index.html file it has: 在其index.html文件中,它具有:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
I tried to move the inline code to an external js file. 我试图将内联代码移至外部js文件。 I copied everything between the "script" tag and put it in a file I named "chat.js".
我在“ script”标记之间复制了所有内容,并将其放入名为“ chat.js”的文件中。 The index.html file and chat.js are on the same level.
index.html文件和chat.js处于同一级别。
So now the same part in the html file looks like this: 因此,现在html文件中的相同部分如下所示:
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="chat.js" charset="utf-8"></script>
and the chat.js file looks like this: chat.js文件如下所示:
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
Based on the discussion, you would have to add the following to your index.js to serve static files in Express. 根据讨论,您必须将以下内容添加到index.js中才能在Express中提供静态文件。
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.use(require('express').static(__dirname)); // Add this to serve static files
Else, it wouldn't able to find where is chat.js thus getting 404 error. 否则,它将无法找到chat.js在哪里,从而得到404错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.