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

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

      })
  }

更新:我在分数递增后将用于将子元素附加到主体元素的代码放入循环内,但这会导致页面上接连打印许多数字。

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

相关文章:

javascript - 单击按钮时, "this"在显示描述函数中如何工作?

javascript - 我的 html 页面上的 google maps api 位置错误

javascript - jsx 三元运算符中的多个条件

javascript - 如何使用 ajax、jquery、php 和 session 更新购物车数量

javascript - 类博客的 Google Firestore 规则

javascript - 在 Javascript 中迭代另一个数组中的一个数组并在 UL 中显示项目

vba - 将集合作为参数发送到过程

javascript - 避免 javascript 的 "this"错误的最佳方法

Jquery Slidedown第一个子级元素

java - StreamCorruptedException : invalid type code: AC