用js簡單實現單詞默寫系統
阿新 • • 發佈:2019-01-08
<h2>單詞默寫系統</h2> <div id="app"> </div> <script> // 定義一個數組 var dataSource = [ { ch: "物件", en: "object", state: false }, { ch: "陣列末尾刪除元素", en: "pop", state: false }, { ch: "刪除物件的屬性", en: "delete", state: false }, { ch: "擷取字元的屬性", en: "slice", state: false } ] //迴圈生成div中的中英文輸入框等 var div = document.getElementById("app"); var str = ""; for (let i = 0; i < dataSource.length; i++) { str += `<div id="app"> <label>${dataSource[i].ch}</label> <input name="en"/> </div>` } div.innerHTML = str + `<div><button onclick="fn()">點選檢查</button></div>`; // button上的點選事件 function fn() { // 獲取lable和input var lables = document.getElementsByTagName("label"); var inputs = document.getElementsByTagName("input"); var arr = []; for (let i = 0; i < lables.length; i++) { arr.push({ ch: lables[i].innerHTML, en: inputs[i].value }) } console.log(arr) //比較 var res = ""; for (let i = 0; i < arr.length; i++) { for (let j = 0; j < dataSource.length; j++) { if (arr[i].ch == dataSource[j].ch && arr[i].en == dataSource[j].en) { res += arr[i].ch + arr[i].en + "\n"; break; } // if(arr[i].en=""||arr[i].en!=dataSource[j].en)alert("error"); // else alert("error"); } } alert(res); } </script>