我正在制作一个游戏,每当你点击该框时,就会出现一个数字图像。
每次用户点击框时,我都会尝试更改背景图片。有九个图像。第一次点击时,图像将更改为img/num1.png
等。第9次点击后,我希望它返回到第一张图像(img/num1.png
)。有没有办法在没有无限循环的情况下做到这一点?
现在它到达第9张图像然后停止。将有四个盒子需要这样做。这就是我所拥有的:
var squareClicks = 0;
$('.numSquares').click(userPicksNum);
function userPicksNum()
{
for(var i = 0; i <= 10; i++)
{
if (squareClicks == 1)
{
//when box is clicked set background image
$(this).attr('src', 'img/num1.png');
squareClicks++
checkNums();
}
else if (squareClicks == 2)
{
$(this).attr('src', 'img/num2.png');
squareClicks++
checkNums[2];
}
else if (squareClicks == 3)
{
$(this).attr('src', 'img/num3.png');
squareClicks++
checkNums[3];
}
else if (squareClicks == 4)
{
$(this).attr('src', 'img/num4.png');
squareClicks++
checkNums[4];
}
else if (squareClicks == 5)
{
$(this).attr('src', 'img/num5.png');
squareClicks++
checkNums[5];
}
else if (squareClicks == 6)
{
$(this).attr('src', 'img/num6.png');
squareClicks++
checkNums[6];
}
else if (squareClicks == 7)
{
$(this).attr('src', 'img/num7.png');
squareClicks++
checkNums[7];
}
else if (squareClicks == 8)
{
$(this).attr('src', 'img/num8.png');
squareClicks++
checkNums[8];
}
else if (squareClicks == 9)
{
$(this).attr('src', 'img/num9.png');
checkNums[9];
squareClicks++
}
}
}
答案 0 :(得分:0)
用以下内容替换问题中显示的整个代码:
var squareClicks = 1;
$('.numSquares').click(userPicksNum);
function userPicksNum() {
if (squareClicks == 10) {
squareClicks = 1 } // resets your counter when the last image is reached
alert(squareClicks); // just for testing, remove this...
$(this).attr('src', 'img/num'+squareClicks+'.png'); //get's the correct img for you
squareClicks++; //sets square clicks up
}
答案 1 :(得分:0)
如果我理解你的问题,你可以做三件事:
1)摆脱for循环。
2)在最后一个if语句中,你可以指定squareClicks = 1;
3)在开始时将squareClicks分配为1
以下是我上面描述的代码版本:
var squareClicks = 1;
$('.numSquares').click(userPicksNum);
function userPicksNum()
{
if (squareClicks == 1)
{
//when box is clicked set background image
$(this).attr('src', 'img/num1.png');
squareClicks++;
}
else if (squareClicks == 2)
{
$(this).attr('src', 'img/num2.png');
squareClicks++;
}
else if (squareClicks == 3)
{
$(this).attr('src', 'img/num3.png');
squareClicks++;
}
else if (squareClicks == 4)
{
$(this).attr('src', 'img/num4.png');
squareClicks++;
}
else if (squareClicks == 5)
{
$(this).attr('src', 'img/num5.png');
squareClicks++;
}
else if (squareClicks == 6)
{
$(this).attr('src', 'img/num6.png');
squareClicks++
}
else if (squareClicks == 7)
{
$(this).attr('src', 'img/num7.png');
squareClicks++;
}
else if (squareClicks == 8)
{
$(this).attr('src', 'img/num8.png');
squareClicks++;
}
else if (squareClicks == 9)
{
$(this).attr('src', 'img/num9.png');
squareClicks=1;
}
}
希望它有所帮助!