Socket.io官方聊天室DEMO的学习笔记
2024-09-22 05:04:02
照着Socket.io官方的聊天室代码敲了一遍,遇到了一个奇怪的问题:
每次点击SEND按钮的时候,都会重新刷新页面。
在点击页面的一瞬间,
看到了正在加载jquery的提示,
然后以为是jquery用的官方cdn的问题导致的,
于是把从官方下载了一个jquery文件放到index.html同级目录,
结果在运行的时候死活找不到jquery文件,这个问题有待解决。
后面认认真真的思考了以下,
SEND按钮其实是没有点击事件的,按钮为啥会点击刷新页面了,
BING搜索了一下关键词:button+刷新页面,
发现果然是button的问题,
只要在button的属性里面加上type="button"那么就不会刷新了。
最终,能够正常跑起来的前端代码是这样子的:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<meta charset="UTF-8">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
var socket = io(); $('form').submit(function(){
socket.emit('message',$('#m').val());
$('#m').val('');
return false;
});
function sendMsg(){
console.log('clicked');
socket.emit('message',$('#m').val());
$('#m').val('');
}
socket.on('connect',function(){
$('#messages').append($('<li>').text("Connected"));
socket.on('dmessage', function(msg){
$('#messages').append($('<li>').text(msg));
});
}); </script>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button type="button" id="sendbtn" onclick="sendMsg(event)" autopostback="false">Send</button>
</form>
</body>
</html>
index.html
最新文章
- DDGSpring2016 Demos
- 【译】Java中的枚举
- POJ 1650 Integer Approximation
- C# 高精度加法 支持小数(待优化)
- Sublime Text3快捷键一览表
- matlab 画图
- 20160409 javaweb 数据库连接池
- Windows下安装Apache2.4+PHP5.4+Mysql5.7
- jqgrid的外观重绘
- kNN算法个人理解
- redis数据库安装及简单的增删改查
- Centos6.8安装zabbix-3.2.6
- PS 滤镜算法原理——碎片效果
- Win7共享文件夹简单?这个共享问题可以难倒90%的人
- [Swift]LeetCode779. 第K个语法符号 | K-th Symbol in Grammar
- python源码为何都是pass
- MySQL数据库性能优化思路与解决方法(二转)
- a*寻路分析
- Android软键盘在清单文件中所有配置含义
- odoo中Python实现小写金额转换为大写金额