按 Enter 键提交消息?

2024-05-12

我正在开发一个基于本教程使用 Meteor 构建的聊天应用程序(http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409 http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409),我试图做到如果您按 Enter 键,它就会提交您的消息,而不必按“发送”按钮。

下面是应用程序用来通过按“发送”按钮提交评论的 JavaScript 代码,但有人知道如何添加输入功能吗?

// when Send Chat clicked add the message to the collection
Template.chatBox.events({
  "click #send": function() {
    var message = $('#chat-message').val();
    chatCollection.insert({
     userId: 'me',
     message: message
   });
   $('#chat-message').val('');

   //add the message to the stream
   chatStream.emit('chat', message);
  }
});
chatStream.on('chat', function(message) {
  chatCollection.insert({
    userId: this.userId,
    subscriptionId: this.subscriptionId,
    message: message
  });
});

您需要检查按键事件。您可以在此处找到每个键的完整代码列表:http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

最好的方法是将单击事件中的函数设为命名函数,然后您可以在两个事件上运行相同的函数。

Template.chatBox.events({
 "click #send": function() {
    var message = $('#chat-message').val();
    chatCollection.insert({
      userId: 'me',
      message: message
    });
    $('#chat-message').val('');

    //add the message to the stream
    chatStream.emit('chat', message);
  },
  "keypress #chat-message": function(e) { 
    if (e.which == 13) {
      console.log("you pressed enter");
      //repeat function from #send click event here
     }
  }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按 Enter 键提交消息? 的相关文章