2

What am I doing wrong here? why writeQuestions doesn't run on-load (not onclick..)?

$(document).ready(function() {

$.getJSON("JavaScript/questions.json", function(data) {questions = data;});
    $("#start").one("click" , writeQuestions);
    writeQuestions();

 });

(the .one() line is commented out in my code)

When i do this:window.onload=writeQuestions; it works fine..

4

3 回答 3

5

writeQuestions() is running before the JSON result is returned. Put the function call in the callback function.

$(document).ready(function() {  
     $.getJSON("JavaScript/questions.json", 
          function(data) { questions = data; writeQuestions(); }
     ); 
}); 

Also, I would recommend updating the writeQuestions() function to accept a parameter, and passing the questions that way. I am surprised it ever worked, since there are variable scope issues.

于 2011-05-19T13:41:05.460 回答
4

Have you tried...

$.getJSON("JavaScript/questions.json", function(data) {
    questions = data;
    writeQuestions();
});

In your example writeQuestions will be called before the getJSON call has returned.

Edit as Fosco pointed out in his answer, you are declaring questions as a global variable here as you do not use the var keyword. This might work but it is not good practice and is bug prone. It would be better to re-write as:

$.getJSON("JavaScript/questions.json", function(data) {
    writeQuestions(data);
});
于 2011-05-19T13:40:29.220 回答
0

are your questions loaded in the .getJSON()? IF so, try putting in a success

$.getJSON("JavaScript/questions.json", function(data) {
    questions = data;
}).success(function() {writeQuestions();)
于 2011-05-19T13:45:49.643 回答