zoukankan      html  css  js  c++  java
  • Socket.io官方聊天室DEMO的学习笔记

    照着Socket.io官方的聊天室代码敲了一遍,遇到了一个奇怪的问题:

    每次点击SEND按钮的时候,都会重新刷新页面。

    在点击页面的一瞬间,
    看到了正在加载jquery的提示,

    然后以为是jquery用的官方cdn的问题导致的,

    于是把从官方下载了一个jquery文件放到index.html同级目录,

    结果在运行的时候死活找不到jquery文件,这个问题有待解决。

    后面认认真真的思考了以下,

    SEND按钮其实是没有点击事件的,按钮为啥会点击刷新页面了,

    BING搜索了一下关键词:button+刷新页面,

    发现果然是button的问题,

    只要在button的属性里面加上type="button"那么就不会刷新了。

    最终,能够正常跑起来的前端代码是这样子的:

     1 <!doctype html>
     2 <html>
     3   <head>
     4     <title>Socket.IO chat</title>
     5     <meta charset="UTF-8">
     6     <style>
     7       * { margin: 0; padding: 0; box-sizing: border-box; }
     8       body { font: 13px Helvetica, Arial; }
     9       form { background: #000; padding: 3px; position: fixed; bottom: 0;  100%; }
    10       form input { border: 0; padding: 10px;  90%; margin-right: .5%; }
    11       form button {  9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
    12       #messages { list-style-type: none; margin: 0; padding: 0; }
    13       #messages li { padding: 5px 10px; }
    14       #messages li:nth-child(odd) { background: #eee; }
    15     </style>
    16   </head>
    17   <script src="/socket.io/socket.io.js"></script>
    18   <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
    19   <script>
    20     var socket = io();
    21     
    22     $('form').submit(function(){
    23         socket.emit('message',$('#m').val());
    24         $('#m').val('');
    25         return false;
    26     });
    27     function sendMsg(){
    28         console.log('clicked');
    29         socket.emit('message',$('#m').val());
    30         $('#m').val('');
    31     }
    32     socket.on('connect',function(){
    33         $('#messages').append($('<li>').text("Connected"));
    34         socket.on('dmessage', function(msg){
    35             $('#messages').append($('<li>').text(msg));
    36         });
    37     });
    38     
    39   </script>
    40   <body>
    41     <ul id="messages"></ul>
    42     <form action="">
    43       <input id="m" autocomplete="off" /><button type="button" id="sendbtn" onclick="sendMsg(event)" autopostback="false">Send</button>
    44     </form>
    45   </body>
    46 </html>
    index.html
  • 相关阅读:
    第八章:数组
    第六章:循环结构(二)
    第五章:循环结构(一)
    第二章:变量 数据类型和运算符
    第三章:选择结构(一)
    第四章:选择结构(二)
    第一章:初识java
    第6章 数据筛选和排序
    第四章 实现Windows程序的数据更新
    第五章 实现Windows程序的数据绑定
  • 原文地址:https://www.cnblogs.com/adoontheway/p/5128004.html
Copyright © 2011-2022 走看看