【发布时间】:2019-04-15 16:58:48
【问题描述】:
所以我有这个蓝图对象:
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。有什么帮助吗?
【问题讨论】:
-
向我们展示点击监听器
-
你在哪里实际增加
currentScore? -
@BhojendraRauniyar 已更新
-
打印次数,因为您在每次点击时都附加。
-
如果我在循环之外执行它,它会保持为 0。你有什么建议?
标签: javascript object this prototype