iT邦幫忙

1

請問要怎麼做才能取得chineseScore 、mathScore 、englishScore的值,並且加起來後除以3的成績,若不及格就顯示紅字,及格就顯示藍字呢

不明 2023-03-12 15:53:281478 瀏覽
  • 分享至 

  • xImage

https://ithelp.ithome.com.tw/upload/images/20230312/201571449RNHXvlDRI.pnghttps://ithelp.ithome.com.tw/upload/images/20230312/20157144rPpAUO0Y5T.png

淺水員 iT邦大師 6 級 ‧ 2023-03-12 17:43:33 檢舉
input 元素要用 .value 存取使用者輸入的值
淺水員 iT邦大師 6 級 ‧ 2023-03-12 17:45:22 檢舉
還有抓下來的值是字串
要轉成數值再計算
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
Vader
iT邦研究生 4 級 ‧ 2023-03-13 16:27:24
<label for="chinese">中文成績:</label>
<input type="number" id="chinese"><br>

<label for="math">數學成績:</label>
<input type="number" id="math"><br>

<label for="english">英文成績:</label>
<input type="number" id="english"><br>

<button onclick="calculate()">計算平均成績</button>

<p id="result"></p>

<script>
function calculate() {
  // 獲取三科成績
  var chineseScore = document.querySelector("#chinese").value;
  var mathScore = document.querySelector("#math").value;
  var englishScore = document.querySelector("#english").value;

  // 計算平均成績
  var averageScore = (parseFloat(chineseScore) + parseFloat(mathScore) + parseFloat(englishScore)) / 3;

  // 根據及格與否設置文字顏色
  var resultElement = document.querySelector("#result");
  if (averageScore >= 60) {
    resultElement.style.color = "blue";
  } else {
    resultElement.style.color = "red";
  }

  // 顯示平均成績
  resultElement.textContent = "平均成績為:" + averageScore;
}
</script>

我要發表回答

立即登入回答