2014-09-04 70 views
0

我可以專注於單擊按鈕時的文本輸入,但它不會專注於頁面第一次加載時的文本輸入,即使我正在使用相同的功能。一旦頁面加載,我怎樣才能在輸入文本框中進行對焦?無法集中在頁面加載

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

爲我工作。 – Rob 2014-09-04 22:34:06

回答

0

嘗試$('.answer').focus();在你準備功能

$(document).ready(function(){ 
    $('.answer').focus(); 
}); 

DEMO:在鍍鉻http://plnkr.co/edit/EX0xS9d8o3TqUqiEOAL5?p=preview

+0

我試過了。當頁面首次加載時,它不會將文本框關注。 DEMO:http://codepen.io/anon/pen/derwi?editors=101 – user3547139 2014-09-04 23:19:17

+0

適合我! :( – 2014-09-04 23:31:18

+0

我嘗試過使用其他瀏覽器,但仍然無法獲得重點加載。但後來我試着另一臺電腦打開同一頁,它的工作。 – user3547139 2014-09-06 18:06:12