【问题标题】:Submit message by pressing enter?按回车提交消息?
【发布时间】:2014-03-20 18:16:44
【问题描述】:

我正在根据本教程 (http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409) 开发一个使用 Meteor 构建的聊天应用程序,并且我正在尝试让它在您按下 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
  });
});

【问题讨论】:

    标签: javascript jquery submit chat enter


    【解决方案1】:
    'keypress #send': function (evt) {
         if (evt.which === 13) {
    

    13 是输入的键码。如果你想改变它,你可以查找javascript keycodes,这样你就可以绑定到任何你喜欢的东西。

    您可能需要考虑熟悉api http://docs.meteor.com/

    【讨论】:

    • 谢谢。我一直在寻找类似的东西来帮助我了解有关 Meteor 的更多信息,现在你找到了,非常感谢!
    【解决方案2】:

    您需要检查按键事件。您可以在此处找到每个键的完整代码列表: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
         }
      }
    });
    

    【讨论】:

    • 感谢这有效并回答了我的问题。还要感谢您解释这一点,而不仅仅是给我代码,因为我正在努力学习这很有帮助:)
    猜你喜欢
    • 2012-03-31
    • 2017-05-16
    • 2014-03-20
    • 2014-07-10
    • 1970-01-01
    • 2016-04-13
    • 2011-05-10
    • 2017-12-28
    相关资源
    最近更新 更多