代码之家  ›  专栏  ›  技术社区  ›  Victor

jquery回发焦点

  •  2
  • Victor  · 技术社区  · 15 年前

    在回发后的页面上,我尝试将焦点返回到以前焦点所在的元素

    $(window).load(function() {
      $('.focus').focus();
    });
    
    $(document).ready(function() {
      $('input:not([type=button],[type=submit]), select, textarea').focus(function() {
        $(this).addClass('focus');
      });
      $('input:not([type=button],[type=submit]), select, textarea').blur(function() {
        $(this).removeClass('focus');
      }); 
    });
    

    我的代码看起来是这样的,它甚至适用于嵌套的元素,但在我看来有点尴尬,我只是想知道是否有一种更好/更优化的方法可以做到这一点?

    1 回复  |  直到 13 年前
        1
  •  1
  •   Alex Sexton    15 年前

    你可以把选择器挂起来 focus dom ready函数中的触发器。您甚至可以尝试将 input 你想要关注的元素,而不是黑名单。

    $(document).ready(function(){
        $('.focus').focus();
        $('input[type=text], select, textarea').focus(function() {
            $(this).addClass('focus');
            // To save the focused value to a hidden field
            $('#id-of-Hidden-Field').val($(this).attr('name'));
    
        }).blur(function() {
            $(this).removeClass('focus');
            // remove the focus hidden field
            $('#id-of-Hidden-Field').val('');
        }); 
    });
    

    但是,我不确定如何保存回发之前焦点所在的元素,以便用 集中 在新页面加载时初始化。如果你 这样做,那么这个代码就可以了。