簡體   English   中英

檢查 HTML 輸入是否正確的有效方法是什么?

[英]What is an efficient way to check if an HTML input is right or wrong?

我正在用 and 創建一個測驗。 由於 JavaScript 代碼的大部分,我發現制作一堆 If / Else 語句效率極低。

這是我的 HTML 代碼:

<!--Question 1-->
<label for="a">A cow says =</label>
<input type="text" id="a"/>

<!--Question 2-->
<label for="a">1 + 1 =</label>
<input type="number" id="b"/>

<button onclick="checkQuiz()">Check Quiz</button>

這是我的 JavaScript 代碼:

var a = document.getElementById("a")
var b = document.getElementById("b")

function checkQuiz() {

// Question 2
   if (a.value == "moo") {
      console.log("correct")
   }
   else {
      console.log("wrong")
   }

// Question 2
   if (b.value == "2") {
      console.log("correct")
   }
   else {
      console.log("wrong")
   }
}

我對一些 Jquery 代碼答案感到失望,只是我對此也不太了解。

制作一個正確答案的數組,並在答案數組中查找問題輸入的索引以比較適當的值。

 // tweak the selector as needed // you'll probably want something more precise const questionInputs = document.querySelectorAll('input'); const correctAnswers = ['moo', '2']; function checkQuiz() { questionInputs.forEach((input, i) => { console.log(`Question ${i + 1}: ${input.value === correctAnswers[i]? 'Correct': 'Wrong'}`); }); }
 <!--Question 1--> <label for="a">A cow says =</label> <input type="text" id="a"/> <!--Question 2--> <label for="a">1 + 1 =</label> <input type="number" id="b"/> <button onclick="checkQuiz()">Check Quiz</button>

暫無
暫無

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

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