How do I get the previously focused element in JavaScript?

前端 未结 7 1728
死守一世寂寞
死守一世寂寞 2021-01-04 03:46

I have an HTML form with multiple text inputs. I want to clear the element that had the focus immediately prior to when the \'Clear\' button is pressed. How do I ge

相关标签:
7条回答
  • 2021-01-04 04:28

    Working on the ideas above, and if you're working with a form, you can define a hidden input and assign it a value of the last focused input's id:

    <input type="hidden" id="focused_element" value="">
    
    $('input:text, textarea').focus(function() {
        $('#focused_element').val($(this).attr('id'));
    });
    

    and then pick up the value at the appropriate later time:

    var focused = $('#focused_element').val();
    
    0 讨论(0)
提交回复
热议问题