简体   繁体   English

通过按Enter提交消息?

[英]Submit message by pressing enter?

I am working on a chat app built with Meteor based off of this tutorial ( http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409 ) and I am trying to make it where if you press enter it submits your message instead of having to press the Send button. 我正在基于本教程( http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409 )使用Meteor构建的聊天应用程序上工作,并且我正在尝试使其在您按输入的位置提交,而不用按“发送”按钮来提交消息。

Below is the javascript code the app uses to submit a comment by pressing the Send button, but does anyone know how to add the enter feature? 以下是应用程序通过按“发送”按钮提交评论的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
  });
});
'keypress #send': function (evt) {
     if (evt.which === 13) {

13 is the keycode for enter. 输入的密码为13。 If you want to change it you can look up the javascript keycodes so you can bind to whatever you like. 如果要更改它,可以查找javascript键代码,以便可以绑定到任何您喜欢的东西。

You might want to consider familiarizing yourself with the api http://docs.meteor.com/ 您可能需要考虑熟悉api http://docs.meteor.com/

You need to check for a key press event. 您需要检查按键事件。 You can find a full list of the codes for each key here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes 您可以在此处找到每个键的代码的完整列表: http : //www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Best way to do this would be make the function in the click event a named function and then you can just run the same function on both events. 最好的方法是将click事件中的函数命名为函数,然后可以在两个事件上运行相同的函数。

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
     }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM