gpt4 book ai didi

JavaScript 函数无法运行

转载 作者:行者123 更新时间:2023-11-28 20:06:00 25 4
gpt4 key购买 nike

我被指示制作一个简单的游戏,点击图像会增加你的分数并最终允许升级。当我单击图像时,它会显示第一次剩余的点击量,但是,后续时间似乎不起作用。这是我的函数相互调用方式的问题吗?

Javascript

//Variables
var clicks = 0;
var level = 2;
var clickInterval = 1;
var holdClick = 0;

function imgClicked() { //Activated by clicking on image
var clicks = clicks + clickInterval; //Increasing clicks
upgradeCheck();
if (holdClick === 1) { //If holding down the image activated
window.onmousedown = holding();
}
}

function upgradeCheck() { //Check if eligible for new level
if (clicks > Math.pow(level, 2)) { //If clicks more than current level^2
level = level + 1; //Next level
upgrade();

} else { //If not
var clicksLeft = Math.pow(level, 2) - clicks; //Determine clicks until eligible
document.getElementById("toUpgrade").innerHTML = clicksLeft + " clicks left until upgrade"; //Display
}
}

function upgrade() { //Upgrading
document.getElementById("clickImg").src = "level" + level + ".png"; //Change to new level
var clickInterval = clickInterval * 2; //Increase points per click
if (Math.pow(level, 2) / clickInterval > 400) { //If it take more than 400 clicks to get to next level
var holdClick = 1; //Activate hold clicking
document.getElementById("message").innerHTML = "You can now hold down the image";
}
}

function holding() {
var clicks = clicks + clickInterval; //Adding more clicks
}

HTML

<p id="toUpgrade"></p>
<img id="clickImg" src="level2.png" onclick="imgClicked()" />
<p> id="message"></p>

最佳答案

我不认为这正在做你认为它正在做的事情:

var clicks = clicks + clickInterval; //Adding more clicks

您没有修改全局 clicks 变量,而是仅在该变量的范围内创建一个名为 clicks全新变量功能。然后,当函数完成时,该变量就会消失。您实际上从未修改现有的 clicks 变量。我认为你想要这个:

clicks = clicks + clickInterval; //Adding more clicks

同样的错误在其他地方也犯过,例如:

var clickInterval = clickInterval * 2; //Increase points per click

和:

var holdClick = 1; //Activate hold clicking

删除 var 关键字以防止声明新变量。

关于JavaScript 函数无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20802596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com