2011-04-11 52 views
0

我有这样的代码在这里:的Javascript没有运行

var Questions=[] 
Questions[0]=["What is the answer?",["A","B","C","D"],3] 
Questions[1]=["What is the answer?",["A","B","C","D"],3] 
Questions[2]=["What is the answer?",["A","B","C","D"],3] 
Questions[3]=["What is the answer?",["A","B","C","D"],3] 

function createQuestions(id) { 
    var tReturn="<form>" 
    tReturn=tReturn+"<b>Questions "+id+":</b>" 

    tReturn=tReturn+"</form>" 
    return tReturn; 
} 

for (i=0;i<4;i++) { 
    var elem=document.getElementById('quiz_section') 
    var func=createQuestion(i) 
    elem.innerHTML=elem.innerHTML+func+"<br />" 
} 

我刚刚使用JavaScript开始。我知道在这里肯定有语法错误,但我找不到它。实际上,在主文档中有一个ID为“quiz_selection”的DIV。

我无法访问任何类型的调试器,因为我在学校,几乎所有的东西都被阻塞了。

如果可以的话,谢谢!

+0

用分号';'结束行是一个好习惯,但这不是语法错误的情况。 – pimvdb 2011-04-11 18:03:46

回答

4

您的功能被命名为createQuestions,但您将其称为createQuestion。否则,语法看起来很好。

此外,如果此代码立即嵌入到您的页面中,它可能无法正常工作,因为执行for循环时文档不会完全存在;因此quiz_section div将不存在。

附上你的循环的功能,像这样:

function initializeQuiz() { 
    for (i=0;i<4;i++) { 
     var elem=document.getElementById('quiz_section') 
     var func=createQuestions(i) 
     elem.innerHTML=elem.innerHTML+func+"<br />" 
    } 
} 

,加入一个onload='javascript:initializeQuiz()'属性您<BODY>标签。

+0

哦,谢谢!我以为我再检查一下! - EDIT:实际上,这样做后,它仍然无法运行。 – FreeSnow 2011-04-11 18:02:41

+0

你能更具体地了解你的结果吗? – 2011-04-11 18:06:29

+0

没有结果,没有任何反应。没有任何代码运行。我试图插入“警报”作为一种方式来判断它打破了什么点,但没有一个显示... – FreeSnow 2011-04-11 18:08:06

3

您定义createQuestions(),然而您打电话给createQuestion(),这自然会抛出ReferenceError

也请在每行之后使用分号。 (良好做法)

2

createQuestion应该createQuestions

1

你可以调整您的问题声明:

var Questions = [ 
    { Question: "What is the answer?", Values: ["A", "B", "C", "D"], Answer: 3 }, 
    { Question: "What is the answer?", Values: ["A", "B", "C", "D"], Answer: 3 }, 
    { Question: "What is the answer?", Values: ["A", "B", "C", "D"], Answer: 3 }, 
    { Question: "What is the answer?", Values: ["A", "B", "C", "D"], Answer: 3 } 
]; 

这样,您就可以访问每个项目作为一个对象:

var question = Questions[0]; 
// question.Question 
// question.Values 
// question.Answer 
+0

我不知道你能做到这一点。谢谢:)为你点:) – FreeSnow 2011-04-11 18:11:50

+0

在这种情况下{}的含义是什么? – FreeSnow 2011-04-11 18:14:48

+1

'{'和'}'大括号定义了一个javascript对象。你应该看看Javascript Object Notation(JSON) – 2011-04-11 18:15:38