On my pages after a postback I am trying to return focus to a previously focused element
$(window).load(function() {
$('.focus').focus();
});
$(document).ready(function() {
$('input:not([type=button],[type=submit]), selec开发者_C百科t, textarea').focus(function() {
$(this).addClass('focus');
});
$('input:not([type=button],[type=submit]), select, textarea').blur(function() {
$(this).removeClass('focus');
});
});
My code looks like this and it works even for nested elements but looks a little awkward to me, I am just wondering if there is a better/more optimal way of doing it?
You can chain the selector and put the focus
trigger in the dom ready function. You might even try whitelisting the types of input
elements you want to focus on instead of blacklist.
$(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('');
});
});
However, I'm not sure how you are saving which element was focused before the postback in order to output it with the focus
class on the new page load. If you are doing that somehow, then this code is fine.
精彩评论