繁体   English   中英

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

[英]How to access newly created object's variable?

所以我有这个蓝图对象:

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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM