gpt4 book ai didi

javascript - 使用javascript拼写游戏得分

转载 作者:行者123 更新时间:2023-11-30 12:51:19 25 4
gpt4 key购买 nike

我有一个使用 JavaScript 的拼写游戏。

目前,当单词拼写正确时,它会显示一条消息。

if(++score >= str.length) {
var text = 'Well done! The correct word is ' + str + '!'
drawBackground(background, images.back, text);
}

我想为每个正确的单词显示一分并增加它。这是我尝试过但没有成功的方法

function points() {
var points = 0;
if(++score >= str.length) {
points++;
document.getElementById("points").innerText="Score: " + points;
}
}

显示分数的 HTML

<p>Score: <span id="points"></span></p>

最佳答案

你的代码有问题:

  • 每次您进入points() 函数时,points 的值都会重置为0。您必须将 var points = 0 移到 points() 之外,使其成为全局变量。
  • 由于函数和全局变量不能同名,因此必须重命名 points 变量(例如,重命名为 numPoints)。
  • The el.innerText property will only work on IE .将其替换为 el.textContent

代码的改进版本:

let numPoints = 0;    

function points() {
if(++score >= str.length) {
numPoints++;
document.getElementById("points").textContent = "Score: " + numPoints;
}
}

关于javascript - 使用javascript拼写游戏得分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20862697/

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