0

我知道它应该获取文本并将其发送到每个套接字,但我不确定每一行的作用。

<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(){
  socket.emit('chat message', $('#m').val());
  $('#m').val('');
  return false;
    });
  });

4

2 回答 2

1
$(function() {
  // create a new socket which connects to `/` by default
  var socket = io()
  // add a submission handler to any form on the current page
  $("form").submit(function() {
    // emit the value stored in the element identified by the id `m` as an argument for the `chat message` event in socket io
    socket.emit("chat message", $("#m").val())
    // clear the value stored in `#m`
    $("#m").val("")
    // prevent event propagation
    return false
  })
})

我想说这段代码有点不正确,因为它会在任何表单提交时触发——如果你有多个表单,你最终会遇到麻烦:)

于 2018-10-27T16:14:21.313 回答
1

// When the document is ready
// jQuery shortcut for $(document).ready(function() {
$(function() {

  // create a new socket and assign it to the socket variable
  var socket = io();

  // when the form is submitted
  $('form').submit(function() {
  
    // emit a "chat message" event containing the value
    // of of the element with the `m` id
    socket.emit('chat message', $('#m').val());
    
    // set that element's value to empty string 
    $('#m').val('');
    return false;
  });
});

于 2018-10-27T16:18:03.250 回答