2014-02-19 106 views
1

我正在使用本教程(http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409)制作与流星的聊天应用程序,如果您按下输入键提交您的评论,而不是每次按发送按键,我都会试图将其设置在其中。按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 
    }); 
}); 

回答

2

您需要捕获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(); } 
    }); 
+0

我会在我的原始文章中的现有代码之后添加这个权限吗?我尝试过,但它不起作用。 – 5AMWE5T

+0

@ user3330382不,你可以用你的代码代替你的代码。另外,如果你想跟随这个词的教程,你可能需要捕捉'textarea'上的'keyup'事件。 –

+0

感谢这有助于 – 5AMWE5T

4

我建议你把你的形式在<form> - 元素,并免费得到这个功能,如果你使用<input> -element而不是<textarea> -element(如果我在<textarea> -element中写入文本时提交了表单,当我按下Enter键时我会发疯!)。只要听取形式submit事件。

+1

不要忘记在提交回调中防止默认 – matb33