提问人:Burakkuboido 提问时间:9/9/2023 更新时间:9/9/2023 访问量:26
在满足条件后如何运行 if 语句?
How do you run an if statement after a condition has been met?
问:
我目前正在尝试在 soulamount 为 10 之后运行一个 if 语句。但是,if 语句仅在 soulamount 为 0 时有效。这是由于 soulamount 一开始就设置为 0。但是,当用户单击按钮时,灵魂量会上升。我假设 if 语句没有按预期工作,因为它在页面加载后立即运行。那么,当 soulamount 达到 10 时,我该如何运行 if 语句?
let soulAmount = 0;
let soulAddition = 1;
let grabSps = document.querySelector(".sps").innerHTML;
let sps = parseInt(grabSps);
let upgradecost1 = 10;
function getSoul() {
soulAmount += soulAddition;
document.querySelector(".souls_amount").innerHTML = soulAmount;
return soulAmount;
}
function upgrade1() {
if (soulAmount >= upgradecost1) {
sps += 1;
soulAmount -= upgradecost1;
document.querySelector(".souls_amount").innerHTML = soulAmount;
document.querySelector(".sps").innerHTML = sps;
return soulAmount;
} else {
alert("You do not have enough souls!")
}
}
window.setInterval(function() {
document.querySelector(".souls_amount").innerHTML = soulAmount += sps;
}, 1000);
if(soulAmount == 10) {
console.log(soulAmount)
}
function achievement1() {
alert("Achievement Unlocked. You've collected 100 Souls!")
document.getElementById("collect100").style.display = "block"
}
我尝试搜索结果,但一无所获。某个地方说不使用赋值运算符,而是使用“==”或“===”,但这没有帮助。最后,我意识到了问题所在,我只是不知道如何克服它。
答:
0赞
imvain2
9/9/2023
#1
我创建了一个名为 validateSoul 的函数,我将其添加到任何正在修改 soul 变量的地方。这样,每当灵魂的价值发生变化时,你就可以验证它的价值并做需要做的事情。
let soulAmount = 0;
let soulAddition = 1;
let grabSps = document.querySelector(".sps").innerHTML;
let sps = parseInt(grabSps);
let upgradecost1 = 10;
function validateSoul(){
if(soulAmount === 10){
console.log("!!!")
}
}
function getSoul() {
soulAmount += soulAddition;
validateSoul();
document.querySelector(".souls_amount").innerHTML = soulAmount;
return soulAmount;
}
function upgrade1() {
if (soulAmount >= upgradecost1) {
sps += 1;
soulAmount -= upgradecost1;
validateSoul();
document.querySelector(".souls_amount").innerHTML = soulAmount;
document.querySelector(".sps").innerHTML = sps;
return soulAmount;
} else {
alert("You do not have enough souls!")
}
}
window.setInterval(function() {
document.querySelector(".souls_amount").innerHTML = soulAmount += sps;
validateSoul();
}, 1000);
function achievement1() {
alert("Achievement Unlocked. You've collected 100 Souls!")
document.getElementById("collect100").style.display = "block"
}
评论
0赞
Burakkuboido
9/9/2023
啊,非常感谢!在寻求帮助之前,我花了几个小时试图弄清楚。我早就应该知道我本来可以这样做的......一定累啊哈哈。谢谢!
评论