Jquery按键调用ajax错误

时间:2014-12-10 16:56:39

标签: jquery ajax

我写了一个事件,按下"输入"提交聊天, 但问题是,事件被调用了2次,而我只按了一次键

$(document).on("keypress",function(event){
        var keycode = (event.keyCode ? event.keyCode : event.which);

        if(keycode == "13")
        {
            var content = $('.khung-nhap #content-div #content').html();
            $.ajax({
                url:"app/namsensei.php",
                type:"post",
                data:{content:content},
                beforeSend:function(){$(".khung-nhap #content-div span").html("Waiting second ...");},
                success:function(dulieu){
                    $('.khung-nhap #content-div #content').html("");
                    $(".khung-nhap #content-div span").html("Type content and press enter");

                }
            });
        }

});

1 个答案:

答案 0 :(得分:0)

实际上您需要将事件仅附加到该表单或输入而不是整个文档。

$('input').on("keypress",function(event){
        var keycode = (event.keyCode ? event.keyCode : event.which);

        if(keycode == "13")
        {
            var content = $('.khung-nhap #content-div #content').html();
            $.ajax({
                url:"app/namsensei.php",
                type:"post",
                data:{content:content},
                beforeSend:function(){$(".khung-nhap #content-div span").html("Waiting second ...");},
                success:function(dulieu){
                    $('.khung-nhap #content-div #content').html("");
                    $(".khung-nhap #content-div span").html("Type content and press enter");

                }
            });
        }

});