在下面的作业中,我已经完成了本章中我能想到的所有内容,但它根本不起作用,我觉得我错过了一些东西,或者我在某个地方搞砸了,因为当我将鼠标悬停在上面时,即使光标也不会改变嵌套列表。
其中一条说明说:
"Using the id property of the list item experiencing the mousedown event, extract the index number with the parseInt() function"
但我的做法似乎并不正确。
window.onload = setup;
function setup() {
var questions = document.querySelectorAll('ol li');
for (var i = 0; i < questions.length; i++) {
questions[i].id = i + "phrase";
questions[i].onmousedown = showEnglish(questions[i]);
questions[i].onmouseup = showFrench(questions[i]);
questions[i].style.cursor = "pointer";
}
}
function showEnglish() {
var phraseNumber = parseInt(questions[i].id);
phraseNumber.innerHTML = english[phraseNumber];
phraseNumber.style.font = "italic";
phraseNumber.style.color = "rgb(191, 22, 31)";
}
function showFrench() {
var phraseNumber = parseInt(questions[i].id);
phraseNumber.innerHTML = french[phraseNumber];
phraseNumber.style.fontStyle = "";
phraseNumber.style.color = "";
}
我收到一条错误消息,提示 questions
未在 questions[i].onmousedown = showEnglish(questions[i]);
处定义,并且
varphraseNumber = parseInt(questions[i].id);
如果这很重要的话,我一直在 Notepad++ 中进行编码。
Html 段:
<ol>
<li>Cet hôtel n'est pas loin de la Tour Eiffel.</li>
<li>A quelle heure arrive le train?</li>
<li>Nous attendons l'autobus depuis une demi-heure.</li>
<li>Ce repas est délicieux.</li>
<li>Quel jour va-t-elle arriver?</li>
<li>Nous avons onze minutes avant le départ du train!</li>
<li>Habiter dans un pays étranger est une bonne expérience.</li>
<li>Excusez-moi! Je suis en retard!</li>
<li>Est-ce que ce taxi est libre?</li>
<li>Faites attention quand vous descendez l'escalier.</li>
</ol>
最佳答案
这不是正确分配事件处理程序的方式:
for (var i = 0; i < questions.length; i++) {
....
questions[i].onmousedown = showEnglish(questions[i]);
...
}
改为:
questions[i].onmousedown = showEnglish;
您将该函数分配为事件处理程序,而不是在该特定时刻调用它。请注意,当您添加括号 fn()
时,您正在调用一个函数。
现在您必须更新 showEnglish()
函数以反射(reflect)这一点。
function showEnglish() {
var phraseNumber = parseInt(this.id); // Here
...
}
请注意,我使用 this
关键字来引用该元素。
同样的过程也适用于 onmouseup
和 showFrench
函数
关于javascript - 为什么我的作业代码中出现 "is not defined"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939716/