button click event is triggered after keypress usi

2019-07-13 15:54发布

I have these codes

$('#search-button').keypress(function (e) {
   if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {            
        search();
   };
});

$('#search-button').bind('click', function () {
   search();
});

under the search module I have an alert, now whenever I press Enter when the button is in focus, the search() under the click event also triggers. Please help. Thanks.

4条回答
够拽才男人
2楼-- · 2019-07-13 16:21

Pressing enter does fire the keypress event - but also triggers the button's 'click' event, so you get search called twice.

You don't need to add a handler for the enter key.

查看更多
我想做一个坏孩纸
3楼-- · 2019-07-13 16:30
    $(document).ready(function(e) {
$('form').bind('keypress', function(event){
    if(event.keyCode == 13)
    {
    event.preventDefault();
    $("#submitcat").click();
    }
});
$("#submitcat").click(function(){
alert("Ok");    
});
});
查看更多
叼着烟拽天下
4楼-- · 2019-07-13 16:39
$(document).on('keypress',function(e) {
    if (e.keyCode == 13 || e.which == 13) {
        var identifier = e.target.id;
        console.log(e.target.id);
        $('#' + identifier).click();
    }
});
查看更多
Viruses.
5楼-- · 2019-07-13 16:42

Why do you put the keypress event on the button? Pressing Enter on it will trigger the click event anyway. You'll probably want to put the keypress event on the text input or drop it altogether.

查看更多
登录 后发表回答