当我单击按钮时,我可以专注于文本输入,但即使我使用相同的功能,它也不会在页面首次加载时关注文本输入。加载页面后,如何在输入文本字段处对焦?
http://codepen.io/anon/pen/derwi
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script>
function generate_question (){
var num1 = Math.floor(Math.random()*10),
num2 = Math.floor(Math.random()*10);
$('.result').hide();
$('.left').html(num1 + ' x ' + num2 + ' = <input type="text" size="3" class="answer">');
$('.answer').val('');
$('.answer').focus();
$('.answer').keypress(function(e){
if (e.which == 13) {
if ($(this).val() == num1 * num2) {
$('.result').html('Very Good!');
$('.result').show();
} else {
$('.result').html('Try Again');
$('.result').show();
}
}
})
}
$(document).ready(function(){
generate_question();
$('#again').click(function(){
generate_question();
});
$('#again').keypress(function(e){
if (e.which == 32){
generate_question();
}
});
})
</script>
</head>
<body>
<div class="content">
<div class="left"></div>
<div class="result"></div>
</div>
<div class="instruction">
Hit enter to check your answer.
<button type='button' id='again' style='margin-top: 10px;'>Do another one?</button>
</div>
</body>
</html>
答案 0 :(得分:0)
在准备好的功能中尝试$('.answer').focus();
$( document ).ready(function(){
$('.answer').focus();
});