英文:
How to confirm if the innerText is equal to something?
问题
I would like to try and confirm the winner of the game. To do this I was planning on using document.getElementById('player1').innerText === 0
to check if player 1 score was equal to zero, but I think the syntax is wrong above. How would I check if the innerText is equal to zero?
function checkWinner() {
if (document.getElementById('player1').innerText === '0') {
message.innerHTML = '<p>${players[1]} you have won the game</p>';
}
if (document.getElementById('player2').innerText === '0') {
message.innerHTML = '<p>${players[0]} you have won the game</p>';
}
}
英文:
I would like to try and confirm the winner of the game. To do this I was planning on using document.getElementById('player1').innerText === 0
to check if player 1 score was equal to zero, but I think the syntax is wrong above. How would I check if the innerText is equal to zero?
function checkWinner() {
if (document.getElementById('player1').innerText === 0) {
message.innerHTML = `<p>${players[1]} you have won the game</p>`;
}
if (document.getElementById('player2').innerText === 0) {
message.innerHTML = `<p>${players[0]} you have won the game</p>`;
}
}
答案1
得分: 2
你可以考虑只使用 === "0"
。
innerText
永远不会是一个数字,它始终是一个字符串。
英文:
You should probably just do === "0"
instead.
innerText
can never be a number, it will always be a string.
答案2
得分: 1
问题在于你使用了===
(严格相等)运算符进行比较,该运算符还会比较操作数的类型。
Element.innerHTML
总是返回一个字符串,而不是一个数字。
所以你的比较是错误的:
"0" === 0 // false
正确的做法是将其与一个零字符串进行比较:
function checkWinner() {
if (document.getElementById('player1').innerText === "0") {
message.innerHTML = `<p>${players[1]} 你赢得了比赛</p>`;
}
if (document.getElementById('player2').innerText === "0") {
message.innerHTML = `<p>${players[0]} 你赢得了比赛</p>`;
}
}
英文:
The problem is that you're comparing using the ===
(Strict equal) operator that will compare operands type too.
The Element.innerHtml
will always return a string, not a number.
So your comparison is false:
"0" === 0 // false
The correct is that you compare against a zero string:
function checkWinner() {
if (document.getElementById('player1').innerText === "0") {
message.innerHTML = `<p>${players[1]} you have won the game</p>`;
}
if (document.getElementById('player2').innerText === "0") {
message.innerHTML = `<p>${players[0]} you have won the game</p>`;
}
}
答案3
得分: 1
'innerHTMLL' 将是一个 'String',但你可以通过添加一个 '+' 符号将其转换为数字:
如果 (+document.getElementById('player1').innerText === 0) {
message.innerHTML = '
' + players[1] + ' 你赢得了比赛
';
}
英文:
As other have said, innerHTMLL
will be a String
, but you may convert it to numeric by adding a +
sign
if (+document.getElementById('player1').innerText === 0) {
message.innerHTML = `<p>${players[1]} you have won the game</p>`;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论