$.focus() not working

后端 未结 14 1188
走了就别回头了
走了就别回头了 2020-11-27 02:48

The last example of jQuery\'s focus() documentation states

$(\'#id\').focus()

should make the input focused (active). I can\'t seem to get

14条回答
  •  臣服心动
    2020-11-27 03:18

    Just in case anybody else stumbles across this question and had the same situation I had - I was trying to set the focus after clicking on another element, yet the focus didn't appear to work. It turns out I just needed an e.preventDefault(); - here's an example:

    $('#recipients ul li').mousedown(function(e) {
        // add recipient to list
        ...
        // focus back onto the input
        $('#message_recipient_input').focus();
        // prevent the focus from leaving
        e.preventDefault();
    });
    

    This helped:

    If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement. Source: https://developer.mozilla.org/en/docs/Web/API/HTMLElement/focus

提交回复
热议问题