我正在尝试解决 javascript 教科书给出的任务。 只要鼠标悬停在五个 div 之一上,代码就应该触发一个事件。只要事件被触发,它就应该计数(当然在 HTML 中显示计数器的变化)。但它显然无法完成工作,我不知道为什么。
希望你能帮到你。
HTML
<div id="one"><a id="pick-one">0</a></div>
<div id="two"><a id="pick-two">0</a></div>
<div id="three"><a id="pick-three">0</a></div>
<div id="four"><a id="pick-four">0</a></div>
<div id="five"><a id="pick-five">0</a></div>
JS
var counter = 0;
function count(event){
counter++; event.target.parentElement.innerHTML = counter;
}
function setup(){
var pages = ["one", "two", "three", "four", "five"];
for (var i = 0; i < pages.length; i++){
document.getElementById("pick-" +
pages[i]).addEventListener("mouseover", count);
}
window.addEventListener("load", setup);
}
最佳答案
删除行 window.addEventListener("load", setup);
并写
setup();
作为脚本的最后一行(并记住在 <body>
底部链接脚本文件)
更新
您的评论:
and actually the code is supposed to count until whatever number, not just from one to five
改变
event.target.parentElement.innerHTML = counter;
到
event.target.innerHTML = counter;
这里正在工作EXAMPLE
关于Javascript,针对父元素 : Why is the event not triggered?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50385597/