jQuery .focusout / .click conflict

后端 未结 3 1006
闹比i
闹比i 2020-12-05 07:19

I\'m working on a project with an autocomplete searchbox. Now I have the issue that I want to pass the value from the found autocompleteresults to the input box, but on the

相关标签:
3条回答
  • 2020-12-05 07:28

    My solution in the similar situation was using timeout to temporarily hold off the action taken in blur event handler. Like this:

    $('#search_field').focusout(function() {
        window.setTimeout(function() { $('#a_c').hide() }, 100);
    });
    
    0 讨论(0)
  • How about using

    :hover

    I solved same problem using it.

    $('className').on('focusout', function(e) {
        if($('.suggestLi' + ':hover').length) {
            return;
        }
        $('.suggestList').empty();
    });
    
    0 讨论(0)
  • 2020-12-05 07:38

    The way I solved this was using the mousedown event instead of click. The mousedown event is always triggered before the focusout event while click is not.

    You can try it out in the little demo below. Focus on the field and then click on the button.

    const field = document.getElementById('field');
    const btn = document.getElementById('btn');
    
    btn.addEventListener('click', () => console.log('Click'));
    btn.addEventListener('mousedown', () => console.log('Mouse down'));
    field.addEventListener('focusout', () => console.log('Focus out'));
    <input id="field">
    <button id="btn">Try it</button>

    As you can see the output is in the following order:

    1. Mouse down
    2. Focus out
    3. Click

    This is the most stable solution without using any workaround hacks like timeouts. It also does not depend on jQuery. The only thing worth noting that mousedown does not wait for the user to release their mouse button, but in terms of user experience that is not really a concern here.

    0 讨论(0)
提交回复
热议问题