How to detect pressing Enter on keyboard using jQuery?

后端 未结 18 2256
有刺的猬
有刺的猬 2020-11-22 11:07

I would like to detect whether the user has pressed Enter using jQuery.

How is this possible? Does it require a plugin?

EDIT: It looks like I need

18条回答
  •  抹茶落季
    2020-11-22 11:29

    I wrote a small plugin to make it easier to bind the "on enter key pressed" a event:

    $.fn.enterKey = function (fnc) {
        return this.each(function () {
            $(this).keypress(function (ev) {
                var keycode = (ev.keyCode ? ev.keyCode : ev.which);
                if (keycode == '13') {
                    fnc.call(this, ev);
                }
            })
        })
    }
    

    Usage:

    $("#input").enterKey(function () {
        alert('Enter!');
    })
    

提交回复
热议问题