【问题标题】:Javascript (html) - getting a variable to have to same value as an img with .srcJavascript (html) - 使用 .src 使变量具有与 img 相同的值
【发布时间】:2015-07-19 15:27:26
【问题描述】:

我正在创建一个显示图像的游戏,如果玩家点击图像,则会调用一个函数来更新统计数据(得分/正确答案/错误答案)。 我将图像存储在一个数组中,并在更新统计函数中将玩家的答案(选择的图像)与数组进行比较。 但是,无论正确与否,玩家的答案总是被归类为错误的,他们永远不会得到任何正确的答案。

请有人检查我的代码,看看他们是否能发现任何明显的错误。非常感谢。

function displayImgs () {
     for(i = 0; i < allCelebs.length; i++){
        document.getElementById("image"+i).src = fullList[i];
    }
}

function updateStats () {
    Answer = document.getElementById("image"+i); 
    var counter = 0;
    while (counter < selectedImages.length) {
        if (Answer==selectedImages[counter]) {
            score+=50;
            correctAnswers+=1;
        } else {
            score-=20;
            incorrectAnswers+=1;
        }
        counter++;
    }
}

以及我在 html 中生成图像的代码:

<script> 
for (count=0;count<16;count++) {
    document.write("<img id='image",count,"' src='blank.jpg' onClick='updateStats();'>"); 
}
</script> 

【问题讨论】:

  • updateStats 中的i 是什么??
  • 更改为 function updateStats ( i ) {onClick='updateStats( count ) ? :-)
  • 传入参数后仍然没有运气:/

标签: javascript html arrays image function


【解决方案1】:

您没有在点击事件中获取正确的元素。您可以将生成器更改为此。注意传递给 updateStat 函数的附加参数。

    for (count=0;count<16;count++) {
        document.write("<img id='image",count,"' src='blank.jpg' onClick='updateStats(",count,");'>"); 
    }

然后您将获得点击哪个图像的参考

function updateStats (index) {
    Answer = document.getElementById("image"+index); 
    var counter = 0;
    while (counter < selectedImages.length) {
        if (Answer==selectedImages[counter]) {
            score+=50;
            correctAnswers+=1;
        } else {
            score-=20;
            incorrectAnswers+=1;
        }
        counter++;
    }
}

【讨论】:

  • 我认为这有点帮助,因为当我检查调试器时,它说 playerAnswer 未定义,而之前,它说'null'。
  • 但是,正确的答案仍然没有正确更新,我很确定这与 document.getElementById("image"+i).src = fullList[i];该图像是 .src 但答案不是,我不确定如何使它们包含相同类型的值,有什么想法吗?谢谢。
  • 如果没有完整的示例,我无法为您提供更多帮助。例如,我无法弄清楚您分配 selectedImages、allCelebs 或 fullList 变量的位置,或者它的值是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多