所以我有这个蓝图对象:
function User (theName, theEmail) {
this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
我创建了一个像这样的新用户 var user1 = new User (theName.value, theEmail.value);
,当用户输入他的姓名和电子邮件时,它位于事件监听器的函数内。现在有问题和下一个问题的按钮。每次用户单击下一个问题按钮时,我想将 currentScore 加一。问题是它始终保持为 0。我这样做是这样的:
scoretag = document.createElement("p");
Scoretag.innerHTML = user1.currentScore;
body.appendChild(scoretag);
事件监听器和主循环:
for (var i = 0; i < theChoices[question1.theChoices].length; i++) {
var arrayQ = document.createElement("p");
arrayQ.innerHTML = theChoices[question1.theChoices][i];
list.appendChild(arrayQ);
var radio = document.createElement("input");
radio.type = "radio";
listOptions.appendChild(radio);
dbtn.addEventListener("click", function() {
//list.removeChild(arrayQ);
//listOptions.removeChild
list.removeChild(list.firstChild);
list.removeChild(list.lastChild);
user1.currentScore = user1.currentScore+1;
scoretag = document.createElement("p");
scoretag.innerHTML = user1.currentScore;
body.appendChild(scoretag);
})
}
更新:我在分数递增后将用于将子元素附加到主体元素的代码放入循环内,但这会导致页面上接连打印许多数字。
但是就像我说的,当我尝试在按钮单击上增加 1 时,它仍然在屏幕上显示 0。有什么帮助吗?
最佳答案
每次增加分数时,都需要更新 HTML 元素。这是一个想法:
function User (theName, theEmail) {
this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
var user1 = new User ("aa","bb");
function updateScore(){
user1.currentScore++;
document.getElementById('score').innerText = user1.currentScore;
}
<button id="btn" onclick="updateScore()">next</button>
<p id="score">0</p>
关于javascript - 如何访问新创建的对象的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271200/