jQuery 在 $(document).ready(function() { 中运行函数
我在这里做错了什么?为什么 writeQuestions
不运行在负载上(而不是 onclick..)?
$(document).ready(function() {
$.getJSON("JavaScript/questions.json", function(data) {questions = data;});
$("#start").one("click" , writeQuestions);
writeQuestions();
});
( .one()
行在我的代码中被注释掉)
当我这样做时:window.onload=writeQuestions;
它工作正常..
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..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
writeQuestions() 在返回 JSON 结果之前运行。将函数调用放在回调函数中。
另外,我建议更新 writeQuestions() 函数以接受参数,并以这种方式传递问题。我很惊讶它竟然有效,因为存在可变范围问题。
writeQuestions() is running before the JSON result is returned. Put the function call in the callback function.
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.
您是否尝试过...
在您的示例中,将在
getJSON
调用返回之前调用writeQuestions
。编辑正如 Fosco 在他的回答中指出的那样,您在此处将
questions
声明为全局变量,因为您不使用var
关键字。这可能有效,但这不是好的做法,而且容易出现错误。最好重写为:Have you tried...
In your example
writeQuestions
will be called before thegetJSON
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 thevar
keyword. This might work but it is not good practice and is bug prone. It would be better to re-write as:您的问题是否已加载到 .getJSON() 中?
如果是这样,请尝试输入成功
are your questions loaded in the .getJSON()?
IF so, try putting in a success