我正在使用。textcontent更改<p>
元素的内容,首先我将整个元素分配给let变量
let player1Score_El = document.getElementById ("score--0").textContent = 0;
当我需要使用另一个变量在点击addEventListener
按钮时携带数字值更改函数内的内容时,问题出现了:
player1Score_El.textContent = score;
然后在控制台中我得到错误消息:
script.js:23 Uncaught TypeError:无法在数字'0'上创建属性'textContent'在HTMLButtonElement。holdFunc (script.js: 23)
我通过从player1Score_El
变量声明中删除.textContent = 0;
来解决这个问题,然后将内容重新分配给全局范围内具有0值的变量。
好了。我将插入有问题的代码和修复后的代码。
有问题的代码:
'use strict';
//setting the needed variables;
let score = 0;
let currentScore = 0;
let currentScore_0El = document.getElementById ("current--0");
let player1Score_El = document.getElementById ("score--0").textContent = 0;
let diceImg = document.querySelector (".dice");
//Setting roll dice button functionl;
const rollDiceFunc = function () {
const diceRoll = Math.trunc(Math.random() * 6) + 1;
currentScore += diceRoll;
currentScore_0El.textContent = currentScore;
diceImg.src = `dice-${diceRoll}.png`;
}
document.querySelector (".btn--roll").addEventListener("click",rollDiceFunc);
// Implementing Hold button function;
const holdFunc = function () {
score = score + currentScore;
player1Score_El.textContent = score;
// console.log(player1Score_El);
currentScore = 0;
currentScore_0El.textContent = currentScore;
}
document.querySelector (".btn--hold").addEventListener ("click", holdFunc);
,下面是修复问题后的代码:
'use strict';
//setting the needed variables;
let score = 0;
let currentScore = 0;
let currentScore_0El = document.getElementById ("current--0");
let player1Score_El = document.getElementById ("score--0");
let diceImg = document.querySelector (".dice");
player1Score_El.textContent = 0;
//Setting roll dice button functionl;
const rollDiceFunc = function () {
const diceRoll = Math.trunc(Math.random() * 6) + 1;
currentScore += diceRoll;
currentScore_0El.textContent = currentScore;
diceImg.src = `dice-${diceRoll}.png`;
}
document.querySelector (".btn--roll").addEventListener("click",rollDiceFunc);
// Implementing Hold button function;
const holdFunc = function () {
score = score + currentScore;
player1Score_El.textContent = score;
// console.log(player1Score_El);
currentScore = 0;
currentScore_0El.textContent = currentScore;
}
document.querySelector (".btn--hold").addEventListener ("click", holdFunc);
我需要理解为什么在变量声明中它不起作用,当我在另一行重新分配player1Score_El
变量的值时,它起作用了?
=
计算赋给它的值。即:
leftHandExpression1 = leftHandExpression2 = someExpression
// equivalent to
leftHandExpression1 = (leftHandExpression2 = someExpression)
// equivalent to
leftHandExpression2 = someExpression;
leftHandExpression1 = someExpression; // assuming no side-effects
在您的代码中,您将0分配给文本内容,因此这就是分配给player1Score_El
的内容。把它分开,这样就不会有链接的=
s,因为这样player1Score_El
是一个实际的元素,而不是0。
我建议永远不要在一条语句中链接=
s -这是令人困惑的阅读,经常是一个打字错误或错误。