2014-02-19 102 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