所以我有这个蓝图对象:

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);

      })
  }


更新:我把分数增加后,在循环内将一个孩子附加到body元素上的代码,但这导致许多数字一个接一个地打印在页面上。

但是就像我说的那样,当我尝试在按钮单击上增加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/

10-11 17:22