如何访问新创建的对象的变量?

时间:2018-11-12 22:46:55

标签: javascript object this prototype

所以我有这个蓝图对象:

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。有帮助吗?

1 个答案:

答案 0 :(得分:1)

每次增加分数时,都需要更新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>