简体   繁体   English

按 Enter 提交评论?

[英]Submit comment by pressing enter?

I am making a chat app with Meteor using this tutorial ( http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409 ) and I am stuck at trying to make it where if you press enter it submits your comment instead of having to press the Send button everytime.我正在使用本教程( http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409 )制作一个与 Meteor 的聊天应用程序,我被困在如果您按 Enter 键,则尝试将其提交到该位置,而不必每次都按“发送”按钮。

Below is the javascript code the app uses to submit a comment by pressing the Send button, but does anyone know what code I need to put in to be able to submit a comment by pressing enter?下面是应用程序用来通过按“发送”按钮提交评论的 javascript 代码,但有没有人知道我需要输入什么代码才能通过按 Enter 提交评论?

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

I would recommend you to place your form in a <form> -element, and get this functionality for free if you use an <input> -element instead of a <textarea> -element (if I wrote text in a <textarea> -element that submitted the form when I pressed enter I would go crazy!).我建议您将表单放在<form> -element 中,如果您使用<input> -element 而不是<textarea> -element(如果我在<textarea>写入文本),则可以免费获得此功能 -当我按下回车键时提交表单的元素我会发疯!)。 Just listen for the forms submit event.只需监听表单submit事件。

You need to capture the keypress event and take the same action therein:您需要捕获keypress事件并在其中执行相同的操作:

 function sendMessage() {
   var message = $('#chat-message').val();
    chatCollection.insert({
     userId: 'me',
     message: message
   });
   $('#chat-message').val('');

   //add the message to the stream
   chatStream.emit('chat', message);
  }

  Template.chatBox.events({
      // Capture the `keyup` event on the `input` element.
      "keyup input": function(ev) {
        if(ev.which === 13) {  // If it was an enter key
          sendMessage();
        }
      },
      "click #send": function () { sendMessage(); }
    });

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

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