我将我的JavaScript与我的HTML文件相关联,因此我不确定为什么在单击此按钮时不会调用函数setUser
。
<!DOCTYPE html>
<html>
<head>
<title>Chat Demo</title>
<link type="text/css" rel="stylesheet" href="client_style.css"/>
</head>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<body>
<h1 class = "text"> THE LEMON LAW </h1>
<div id="error-container" ></div>
<div style="text-align:center">
<ul style="list-style-type: none;" >
<li><input id="name" type="text" name="name" value="" placeholder="Enter your Name!" ></li>
<li><input id="age" type="text" name="age" value="" placeholder="Enter your Age!" ></li>
<li><input id="gender" type="text" name="gender" value="" placeholder="Enter your Gender!" ></li>
</ul>
<button type="button" name="button" onclick="setUser()">Start chating!</button>
</div>
<script type="text/javascript" src="/public/chat.js"></script>
</body>
</html>
这是我在javascript文件中的功能
function setUser(){ // set username event listener
name = document.getElementById('name').value;
age = document.getElementById('age').value;
gender = document.getElementById('gender').value;
//send user name to server
socket.emit('setUser', {name:name , age:age, gender:gender});
};
答案 0 :(得分:0)
问题是您尚未在客户端代码中定义socket
。
在这里尝试一下。
html 文件
//请注意,我使用了socket.io
和jquery
的在线路径。您不需要使用它们。您可以继续使用自己的<script>
参考
<!DOCTYPE html>
<html>
<head>
<title>Chat Demo</title>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="new.js"></script>
</head>
<body>
<h1 class = "text"> THE LEMON LAW </h1>
<div id="error-container" ></div>
<div style="text-align:center">
<ul style="list-style-type: none;" >
<li><input id="name" type="text" name="name" value="" placeholder="Enter your Name!" ></li>
<li><input id="age" type="text" name="age" value="" placeholder="Enter your Age!" ></li>
<li><input id="gender" type="text" name="gender" value="" placeholder="Enter your Gender!" ></li>
</ul>
<button type="button" name="button" onclick="setUser()">Start chating!</button>
</div>
</body>
</html>
new.js 档案
//使用正确的文件名参考。我刚用新的作为例子。
function setUser(){ // set username event listener
name = document.getElementById('name').value;
age = document.getElementById('age').value;
gender = document.getElementById('gender').value;
var socket = io.connect('http://localhost');
socket.emit('setUser', {name:name , age:age, gender:gender}); //send user name to server
console.log("setUser Called"); //to check if it's calling this function. Just used to show you.
};
调用该函数,套接字尝试连接到主机。在定义socket
时你必须确定。我已连接到localhost
Apache server
定义套接字的标准方法是:
var socket = io.connect('http://localhost:8090');
//io is a global variable and hence no need to define it.
这里注意我们还定义了端口号。8090
仅用作示例