首页 > 解决方案 > 使用函数阻止了我的代码工作?

问题描述

我附上了之前的代码和之后的代码。代码是,如果答案正确,则弹出 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);}
}}

标签: javascripthtml

解决方案


问题在于这些行:

setTimeout(hide("correct"),1000);

您必须传递对 的函数引用setTimeout()但您传递的是函数调用。结果是hide()立即被调用,并且该调用的返回值是然后被传递给setTimeout(). 由于hide没有返回值,undefined正在被传递。

将行更改为:

setTimeout(function(){hide("correct")},1000);

这样您就可以传递本身将调用的匿名函数声明hide


推荐阅读