我希望"继续播放"按钮重新加载游戏,但保持分数。单击按钮后,它会保留分数,但在单击形状后没有给出正确的答案。我在这里错过了什么?下面是我的代码,您也可以在jsFiddle中查看它以查看它的实际效果。
var shapeName = ["Square", "Rectangle"];
var score = 0;
var cssIdSquare = "<div id='square' onclick='sqrClick()'></div>";
var cssIdRec = "<div id='rect'onclick='rectClick()' ></div>";
var docMyAnswer = document.getElementById("myAnswer");
var docMyScore = document.getElementById("score");
var answerCorrect = "CORRECT!";
var answerWrong = "WRONG!";
// Random Shape to Select Title
var shapesTitle = shapeName[Math.floor(Math.random() * shapeName.length)];
document.getElementById("IdShapeTitle").innerHTML = shapesTitle.toString();
///// Function Shape Logic
function showAllShapes() {
///// Show both shapes
document.getElementById("showShapes").innerHTML = cssIdSquare + "<br>" + cssIdRec;
}
function sqrClick() {
if (shapesTitle === "Square") {
docMyAnswer.innerHTML = answerCorrect;
score += 1;
docMyScore.innerHTML = score;
}
if (shapesTitle === "Rectangle") {
docMyAnswer.innerHTML = answerWrong;
}
}
function rectClick() {
if (shapesTitle === "Rectangle") {
docMyAnswer.innerHTML = answerCorrect;
score += 1;
docMyScore.innerHTML = score;
}
if (shapesTitle === "Square") {
docMyAnswer = answerWrong;
}
}
showAllShapes();
// Continue Playing Button
function btnContPlay() {
var shapesTitle = shapeName[Math.floor(Math.random() * shapeName.length)];
document.getElementById("IdShapeTitle").innerHTML = shapesTitle.toString();
showAllShapes();
}
// Start Over Button
function btnStartOver() {
score = 0; // reset score to 0
document.getElementById("score").innerHTML = score;
location.reload();
}
http://jsfiddle.net/arevee/39rgqevy/
***如果您有任何缩短代码的提示,我想听听。另外我想保留这个功能,我的下一个项目将是学习对象。
答案 0 :(得分:0)
您的问题出在shapeTitle variable
。在btnContPlay()
内部功能,您有一个新的shapeTitle
变量,因为您已使用var
关键字开始使用该变量。您的sqarClick
并且rectClick
函数无权访问此新创建的变量。 请记住,在javascript函数中创建自己的范围 。您的第一个shapeTitle
变量位于 全局范围 。
您的btnContPlay()
功能是:
function btnContPlay() {
var shapesTitle = shapeName[Math.floor(Math.random() * shapeName.length)];
document.getElementById("IdShapeTitle").innerHTML = shapesTitle.toString();
showAllShapes();
}
将其更改为
function btnContPlay() {
shapesTitle = shapeName[Math.floor(Math.random() *shapeName.length)]; //removed var from shapesTitle
document.getElementById("IdShapeTitle").innerHTML = shapesTitle.toString();
showAllShapes();
}
因此,如果没有var
关键字,它就不会在函数范围内创建新变量,现在它会影响全局shapeTitle
变量。这是scope相关的problem.Removing它将解决您的问题。 jsfiddle