簡體   English   中英

如何將分數顯示為可以從 Javascript 更新的 HTML 標簽?

[英]How to display score as an HTML tag that can be updated from Javascript?

所以我正在開發一個測驗應用程序,需要一種在屏幕上顯示分數的方法,該方法可以從錯誤/正確答案的 onclick 事件中更新。 由於我是編程新手,並且在 HTML 方面非常糟糕,我該怎么做? 這是一些上下文的代碼片段:

<h1 style = "position:relative;left:10px;color:#DDDDDD"> SCORE: <span id = "score"> 0 </span>  </h1> //the score h1 tag with the actual score

document.getElementById("r1").addEventListener("click", function(){
  score.innerHTML += 10 //supposed to increase score but isn't working as intended
  r1.remove() //remove the buttons with the answers to free space for the next questions
  r2.remove()
  r3.remove()
  q.remove()


 }) //an onclick event listener on a button with the right answer to a question

如果要更新分數,請使用parseInt(document.querySelector('.class').innerHTML)從元素中加載分數,以便獲得integer 您需要一個 integer 字符串才能實際使用它進行計算。 否則你會得到一個NaN (不是數字)錯誤。 然后使用.innerHTML = element + 10; .innerHTML = element - 10;

 function correct() { let score = parseInt(document.querySelector('.score').innerHTML); document.querySelector('.score').innerHTML = score + 10; } function incorrect() { let score = parseInt(document.querySelector('.score').innerHTML); document.querySelector('.score').innerHTML = score - 10; }
 <button onclick="correct()">Correct Anwser</button> <button onclick="incorrect()">False Anwser</button> <p>Score: <span class="score">0</span></p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM