[英]im trying to change the value of a text inside an if statement but it doesnt work i think i use wrong logic
So i have made this code that when i click the check button it changes the text of message every time , depending on the number input in guess variable .所以我制作了这段代码,当我单击检查按钮时,它每次都会更改消息文本,具体取决于猜测变量中输入的数字。
Though my logic to declare the variables in the beggining and then use them seems okey to me, it doesnt work Can someone explain why my logic is wrong?虽然我在开始时声明变量然后使用它们的逻辑对我来说似乎没问题,但它不起作用有人可以解释为什么我的逻辑是错误的吗?
// for example i declared
let message = document.querySelector('.message').textContent;
//and then i used message inside if to change the text
message = '‼ Type a Number';
why is this wrong?为什么这是错的?
document.querySelector('.check').addEventListener('click', function () {
let score = 20;
const guess = Number(document.querySelector('.guess').value);
let message = document.querySelector('.message').textContent;
if (!guess) {
message = '‼ Type a Number';
} else if (secretNumber === guess) {
message = 'You Won 🥳';
} else if (secretNumber < guess) {
message = 'It is a lower Number!';
score += -1;
document.querySelector('.score').textContent = score;
} else if (secretNumber > guess) {
message = 'It is a higher Number!';
score += -1;
document.querySelector('.score').textContent = score;
}
});
Your problems (or the two that jump out at me) are that you redefine score
every time the function is run.您的问题(或两个跳出来的问题)是每次运行函数时都重新定义
score
。 That is, every time you click the button, score
is reset to 20 and can only take on values of 20
or 19
depending on the user's input.也就是说,每次单击按钮时,
score
都会重置为 20,并且只能取20
或19
的值,具体取决于用户的输入。 The other problem is you never re-assign the textContent
of the .message
element.另一个问题是您永远不会重新分配
.message
元素的textContent
。
To resolve this, just move that declaration of score
outside of the function and add an extra message reassignment line like so:要解决这个问题,只需将
score
声明移到函数之外并添加额外的消息重新分配行,如下所示:
let score = 20;
document.queyrSelector(".check").addEventListener("click", function() {
// the 'let score' line has been removed from in here
const guess = Number(document.querySelector('.guess').value);
let message = document.querySelector('.message').textContent;
// Rest of your code ...
document.querySelector(".message").textContent = message;
});
Also note (as Bravo pointed out ) that your use of +=
and -
overlaps - you should just use the compound assignment operator with subtraction (ie, score -= 1
not score += -1
. This also works for other operators, such as multiplication *=
and division /=
.)另请注意(正如Bravo 指出的那样),您使用
+=
和-
重叠 - 您应该只使用带有减法的复合赋值运算符(即score -= 1
而不是score += -1
。这也适用于其他运算符,例如作为乘法*=
和除法/=
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.