LoginSignup
0
0

More than 1 year has passed since last update.

DOM操作、WINDOWオブジェクトのみでの英単語システム作成方法

Last updated at Posted at 2022-12-06

本記事はDOM操作、WINDOWオブジェクトによるランダム英単語作成システムの作成方法に関して紹介しています。

まず、クリックしたらランダムな単語テストを表示する機能を作成します。

htmlでテスト作成ボタンを作ります。

<button id="buttonid">作成</button>

そしたら、DOM操作を使ってバタンのidを取得します。

let button = document.getElementById('buttonid');

ボタンのidはgetElementByIdで取得します。

次にaddEventListenerでクリックされた時の処理を作成します。

この前にhtml内にテーブルを作成する素地を作っておきます。

<p>Transelate English to Japanese.</p>
            <table id = "testTable" border="1" width="500">
                <tr>
                    <th>word</th>
                    <th>answer</th>
                </tr>
            </table>

問題となる単語を格納する配列を作成します。

wordList=['word1','word2','word3'];

ランダムな数を作成する関数を作成します。

var randoms = [];
var min = 1, max = wordList.length-3; 
for(i = min; i <= max; i++){
  while(true){
    var tmp = intRandom(min, max);
    if(!randoms.includes(tmp)){
      randoms.push(tmp);
      break;
    }
  }
} 
function intRandom(min, max){
  return Math.floor( Math.random() * (max - min + 1)) + min;
}

そしたら、いよいよランダムテスト作成システムを作っていきます

button.addEventListener('click',function(e){
    alert('test creating start.');
    for(let i=0;i<11;i++){
        let tbl = document.getElementById("testTable");
        let row = document.createElement("tr");
        let cellText = '';
        for (let j=0; j<2; j++){
            let cell = document.createElement('td');
            if(j===0){
                cellText  = document.createTextNode(wordList[randoms[i]]);
            }else{
                 cellText = document.createTextNode('                ');
            }
            cell.appendChild(cellText);
            row.appendChild(cell);
        }
                tbl.appendChild(row);
    }
},false);

最後に作成した英単語テストを印刷する機能を作成します。

<button id="buttonid2">印刷</button>

印刷はWindowオブジェクトのwindow.print()を使います。

let print_button = document.getElementById('buttonid2');
print_button.addEventListener('click',function(e){

  window.print();
});

style.visiblyを使うとよりいい感じに作れると思います!

実際に作成したコードの一部を改変して記載しているのでコピペして使用した場合バグが発生する可能性があります。予めご了承ください。

こちらが実際に作成したシステムです。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0