weixin_33743661 2017-03-09 09:23 采纳率: 0%
浏览 91

jQuery keydown无法正常工作

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/203198/event-binding-on-dynamically-created-elements" dir="ltr">Event binding on dynamically created elements?</a>
                            <span class="question-originals-answer-count">
                                (23 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2017-03-09 09:39:09Z" class="relativetime">3 years ago</span>.</div>
        </div>
    </aside>

I am trying to make a press enter to send data using jquery but my code is not working. Anyone can tell me what i am missing here ?

<textarea name="reply" class="reply" id="replyChat" placeholder="Write your message"></textarea>

JS

function SendMessage() { 
       $.ajax({
        type: "POST",
        url: "/ajax/reply",
        data: dataString,
        cache: false,
        success: function(html) {
            $('.messages-body').append(html);
        }
      });
     }

   $('#replyChat').bind('keydown', function(e) {
      if(e.keyCode==13) {
        SendMessage();
    }
  });
  $('body').on("click",".reply-btn",function() {
     SendMessage();
 });

Click function is working fine just keydown doesn't work here.

</div>
  • 写回答

1条回答 默认 最新

  • George_Fal 2017-03-09 09:31
    关注

    Use event delegation for the dynamically generated element, although use event.which property which is suggested by jQuery.

    function SendMessage() {
      console.log('hi');
      // replace with your ajax code
    }
    
    $('body').on('keydown', '#replyChat', function(e) {
      if (e.which == 13) {
        SendMessage();
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea name="reply" class="reply" id="replyChat" placeholder="Write your message"></textarea>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog