带按键的js问题输入不发送文本

时间:2019-03-06 19:14:13

标签: javascript

大家好,抱歉给您带来麻烦,因为按键问题,即时通讯正试图进行网络聊天,并且当按Enter时,文本仍在文本框中,但是当我单击按钮时,它会发送消息,并且不要从中删除消息文本框是我的代码:

       $("#txtmessage").keypress(function (e) {
            if (e.which == 13) {
                $('#btnSendMsg').click();
            }
        });


        $('#btnSendMsg').click(function () {

            var msg = $("#txtmessage").val();
            if (msg.length > 0) {

                var userName = $('#hdUserName').val();

                var date = GetCurrentDateTime(new Date());

                chatHub.server.sendMessageToAll(userName, msg, date);
                $("#txtmessage").val('');


            }
        });

2 个答案:

答案 0 :(得分:0)

您保留副本:

$("#txtmessage").keypress(function (e) {
            console.log();
            var keycode = (e.keyCode ? e.keyCode : e.which);
            if (e.which == 13) {

                var msg = $("#txtmessage").val();
                if (msg.length > 0) {
                var userName = $('#hdUserName').val();
                var date = GetCurrentDateTime(new Date());
                chatHub.server.sendMessageToAll(userName, msg, date);
                $("#txtmessage").val('');

            }
        });

或创建一些发送功能:')

答案 1 :(得分:0)

可能是HTML的问题,可能是您正在使用的元素ID与页面中的实际元素ID不匹配。代码有效,请参见下文:

const chatHub = {
         server: {
           sendMessageToAll: function(userName, msg) { 
            console.log(arguments)
           }
         }
       }
       
       function GetCurrentDateTime(date) {return +date}
       
       $("#txtmessage").keypress(function (e) {
            console.log();
            var keycode = (e.keyCode ? e.keyCode : e.which);
            if (e.which == 13) {
                $('#btnSendMsg').click();
            }
        });


        $('#btnSendMsg').click(function () {

            var msg = $("#txtmessage").val();
            if (msg.length > 0) {

                var userName = $('#hdUserName').val();

                var date = GetCurrentDateTime(new Date());

                chatHub.server.sendMessageToAll(userName, msg, date);
                $("#txtmessage").val('');


            }
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSendMsg">send</button>

<input type="hdUserName" placeholder="User name" value="foo" />
<input type="text" id="txtmessage" placeholder="Text message" />