2012-11-17 51 views
0

这是怎么回事? 在我头上的标签......为什么我的功能没有定义?

var movieArray = [ 
["Everything is Illuminated", "0", ""], 
["The Girl Who Leapt Through Time (Toki wo kakeru shojo)", "1", "<ol><li><span class=\"bold quote_actor\">Kosuke Yoshiyama: </span><span class=\"line\">It&#039;s not that rare. Many girls do it at your age.</span></li>            </ol>"], 
["Freedom Writers", "0", ""], 
["Inside Man", "0", ""] 
]; 

function checkAnswer(this.value) { 
    if (this.value == 0) { 
     alert ("Wrong answer!"); 
    } else { 
     alert ("Correct Answer!"); 
    } 

} 

在身体...

<p><a id="0" class="btn btn-primary btn-large" value="0" onclick="checkAnswer(this.value)">Everything is Illuminated</a></p> 
<p><a id="1" class="btn btn-primary btn-large" value="1" onclick="checkAnswer(this.value)">The Girl Who Leapt Through Time (Toki wo kakeru shojo)</a></p> 

的错误是没有定义checkAnswer()。怎么来的?

谢谢。

+4

你确定你没有得到更多的错误吗? '函数checkAnswer(this.value)'不是有效的JavaScript,它需要'function checkAnswer(value)' –

+0

你在哪里可以看到这个错误? – ted

+0

你知道你的第二部电影里有双引号,对不对?如果将它全部定义在全局范围内,那么这将使所有事件都崩溃并烧毁... – Norguard

回答

3

你忘了加上反斜线

var movieArray = [ 
    ["Everything is Illuminated", "0", ""], 
    ["The Girl Who Leapt Through Time (Toki wo kakeru shojo)", "1", "<ol><li><span class=\"bold quote_actor\">Kosuke Yoshiyama: </span><span class=\"line\">It&#039;s not that rare. Many girls do it at your age.</span></li>            </ol>"], 
    ["Freedom Writers", "0", ""], 
    ["Inside Man", "0", ""] 
    ]; 

function checkAnswer(arg1) { 
    if (arg1 == 0) { 
     alert("Wrong answer!"); 
    } else { 
     alert("Correct Answer!"); 
    } 

}​ 

其次this.value逃脱"数组元素的内部,而调用checkAnswer(在defitinion的时间应传递),而不是

+2

您的答案如何获得用户在问题中从未指定的数据? –

+0

@Cthulhu OP删除了那些数据,它原来就在那里。 –

+0

你可能还提到'this.value'不是一个正确的函数参数 –

2

怎么每个人都错过了this.value在参数列表中?它应该是一个标识符,如myvalue。这就是没有定义checkAnswer的原因。

现在,至于其余的代码,您不能在checkAnswer函数中使用this,因为它将引用全局对象,而不是链接。此外,链接不支持value属性,因此您需要使用getAttribute或直接将该值放入onClick事件中。

function checkAnswer(myval) { 
    if (myval == 0) { 
     alert ("Wrong answer!"); 
    } else { 
     alert ("Correct Answer!"); 
    } 
} 

<p><a class="btn btn-primary btn-large" onclick="checkAnswer(0)">Everything is Illuminated</a></p> 
<p><a class="btn btn-primary btn-large" onclick="checkAnswer(1)">The Girl Who Leapt Through Time (Toki wo kakeru shojo)</a></p> 

我也去掉了id属性,因为开头的号码的ID是无效的,除非HTML5(即使如此,他们不是一个好主意,因为旧的浏览器仍然在广泛使用,甚至没有他们没有意义)

+0

感谢您的额外信息。我没有意识到你提到的事情,但是我从中学到了很多东西。 – Leke

0

函数语法错误。

错误:

function checkAnswer(this.value) { 

甲函数的语法必须是functionName(formalParameterName)。你正在一个函数参数中传递一个对象的值,这将导致错误。您必须将其更改为function checkAnswer(param)