How do I keep a form in focus when a new one is ad

2019-08-30 11:28发布

问题:

Here's a fiddle: FIDDLE

function blanker(){ 
    var c = $('.whatever').html().replace("thisWillBlank", "<form><input type='text' 
            id='thisWillBlank'></form>");
    $('.whatever').html(c); 
}

$('#alreadyBlanked').focus(); 

setTimeout(function(){blanker()}, 3000); 

Using JS/jquery/css I would just like for whichever form that has been clicked on, to remain in focus even if new ones appear. Thanks.

回答1:

You're replacing the elements, so the old element is no longer available, but as long as it has an ID, you can target that instead:

function blanker(){ 
    var active = document.activeElement.id;
    var c = $('.whatever').html().replace("thisWillBlank", "<form><input type='text' id='thisWillBlank'></form>");
    $('.whatever').html(c); 
    $('#'+active).focus();
}

FIDDLE