javascript - 使用函数阻止了我的代码工作?
问题描述
我附上了之前的代码和之后的代码。代码是,如果答案正确,则弹出 div 会出现第二次说正确,如果答案错误,则弹出 div 会出现第二次说错误。
我决定通过使用函数来隐藏和显示 div 并使用变量 id 来传递 div id 并在我需要隐藏或取消隐藏 div 时调用它来改进代码,因为在整个代码中我一直在隐藏和取消隐藏 div。
但由于某种原因,这些函数适用于此新代码中接受的所有其他 div。分数变量增加,分数的内部 html 更新只是“错误”和“正确”的 div 不显示,然后在一秒钟后隐藏。
前,
function hideCorrectBox(){
document.getElementById("correct").style.display='none';
}
function hideWrongBox(){
document.getElementById("wrong").style.display='none';
}
document.getElementById("box1").onclick=function(){
if(areWePlaying==true){
if(document.getElementById("box1").innerHTML==answer){
document.getElementById("correct").style.display='initial';
setTimeout(hideCorrectBox,1000);
score= score+1;
document.getElementById("scoreValue").innerHTML= score;
newQuestion();
}
else {document.getElementById("wrong").style.display='initial';
setTimeout(hideWrongBox,1000);}
}}
后,
function show(Id){
document.getElementById(Id).style.display="initial";
}
function hide(Id){
document.getElementById(Id).style.display="none";
}
document.getElementById("box1").onclick=function(){
if(areWePlaying==true){
if(document.getElementById("box1").innerHTML==answer){
show("correct");
setTimeout(hide("correct"),1000);
score= score+1;
document.getElementById("scoreValue").innerHTML= score;
newQuestion();
}
else {show("wrong");
setTimeout(hide("wrong"),1000);}
}}
解决方案
问题在于这些行:
setTimeout(hide("correct"),1000);
您必须传递对 的函数引用,setTimeout()
但您传递的是函数调用。结果是hide()
立即被调用,并且该调用的返回值是然后被传递给setTimeout()
. 由于hide
没有返回值,undefined
正在被传递。
将行更改为:
setTimeout(function(){hide("correct")},1000);
这样您就可以传递本身将调用的匿名函数声明hide
。
推荐阅读
- reactjs - 打字稿错误“typeof DefaultTheme”类型上不存在属性“div”
- java - 为什么 Jenkins 管道抛出 java.lang.ClassNotFoundException: com.mysql.jdbc.Driver?
- javascript - 无法读取地图未定义反应的属性
- firebase - 颤振火力,列表
不是列表类型 - codeigniter - 如何使用不同的数据库表制作注册表单codeigniter
- amazon-web-services - AWS API 网关测试
- django - 在 UpdateView 中更改 django 绑定数据
- qt - 如果单击 QTableView 的单元格,则发出信号
- oracle - 如何修复使用 oracle 数据库在 utl_http 响应中获取不可读字符的问题?
- c - 如何在 MinGW gcc 中捕获断言失败?