[英]How does the 'prototype' object have access to the newly created object for 'this'?
[英]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.