2010-02-22 72 views
2

在回传后,我的网页我想将焦点返回到先前的焦点内容jQuery的回传焦点

$(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

您可以链接选择器并将focus触发器设置为dom就绪功能。您甚至可以尝试将您要关注的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(''); 
    }); 
}); 

不过,我不知道你是如何保存这些元素被回发之前,为了它在新的页面加载focus类重点输出。如果你这样做,那么这段代码很好。

+0

感谢您的回复。你是对的,看起来这是我需要做的 - 添加一个隐藏的字段并将其保存在那里,除非有更好的方法。 – Victor 2010-02-22 19:40:05

+0

如果你喜欢答案,你应该标记它是正确的。 :) – 2010-02-22 20:22:49

+0

我肯定会的。但是,如果你能告诉我如何使用隐藏领域保存集中控制,因为它似乎是最好的选择,我将不胜感激。 – Victor 2010-02-22 20:28:01